Reputation: 1748
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:
Let's not just solve for 666666.....
I want it to be generic for any number. How about 7777777777....
or 44444........
or 55555...
?
String operations are worse, the increase from current complexity of O(n)
to O(n^2)
.
Upvotes: 2
Views: 335
Reputation: 414285
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)
.
Upvotes: 0
Reputation: 316
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)
Upvotes: 6
Reputation: 4021
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)))
Upvotes: 1