2

I have an interesting problem where I want to generate a big number (~30000 digits) but it has to be all identical digits, like 66666666666666.......

So far I have done this by:

def fillWithSixes(digits):
    result = 0
    for i in range(digits):
        result *= 10
        result += 6
    return result

However, this is very inefficient, and was wondering if there is any better way? Answer in cpp or java is okay too.

Edit:

  1. Let's not just solve for 666666..... I want it to be generic for any number. How about 7777777777.... or 44444........ or 55555...?

  2. String operations are worse, the increase from current complexity of O(n) to O(n^2).

wythagoras
  • 316
  • 8
  • 16
Nick
  • 1,692
  • 3
  • 21
  • 35
  • what do you mean by unique digits.... also, you can instead make `result` a string and concatenate with `result += '6'` then return `int(result)` but if the number is as big as you said, I'm pretty sure that will reach the `int` limit – R Nar Nov 16 '15 at 20:35
  • 2
    or, even better, just `return int('6'*digits)` since `'str'*int = 'strstrstr...'#int times` – R Nar Nov 16 '15 at 20:36
  • 1
    @RNar - python's Ints are arbitrarily big. `int('6' * 10000)` works great. – Seth Nov 16 '15 at 20:45
  • [depends on your version of python](http://stackoverflow.com/questions/7604966/maximum-and-minimum-values-for-ints) – R Nar Nov 16 '15 at 20:46

3 Answers3

6

You may use the formula 666...666 = 6/9*(10**n-1), where n is the number of digits.

So, in Python, you would write that as

n = int(input())
a = 6 * (10**n - 1) // 9
print(a)
jfs
  • 399,953
  • 195
  • 994
  • 1,670
wythagoras
  • 316
  • 8
  • 16
1

You can use ljust or rjust:

number = 6
amount_of_times_to_repeat = 30000
big_number = int("".ljust(amount_of_times_to_repeat, str(number)))
print big_number

In one single line:

print int("".ljust(30000, str(6)))

Or:

new_number = int("".ljust(30000, str(6)))
Andrés Pérez-Albela H.
  • 4,003
  • 1
  • 18
  • 29
0

The fastest method to generate such numbers with 100000+ digits is decimal.Decimal():

from decimal import Decimal as D

d = D('6' * n)

Measurements show that 6 * (10**n - 1) // 9 is O(n*log n) while D('6' * n) is O(n). Though for small n (less than ~10000), the former can be faster.

Decimal internal representation stores decimal digits directly. If you need to print the numbers latter; str(Decimal) is much faster than str(int).

Community
  • 1
  • 1
jfs
  • 399,953
  • 195
  • 994
  • 1,670