Nick
Nick

Reputation: 1748

Fastest way to generate number like 66666 when the number of digits is given

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).

Upvotes: 2

Views: 335

Answers (3)

jfs
jfs

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

wythagoras
wythagoras

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

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

Related Questions