-2

I am writing a program for counting number of digits in a non negative integer whose upper bound is 10^{1000000} and has a time limit of 12 seconds I have declared an array with size 1000000 and the indexes 0,1,2...,1000000 correspond to the number of digits of the number represented by 10^{array index}. However I am getting Time Limit Exceeded for input ranges close to 10^{10000}. Please find inline the code for the same:

def Number(x):
    a=[0]*(1000000)
    for j in xrange(len(a)):
        #print j
        a[j]=j+1
    i=0
    flag=0
    flagc=0
    counter=0
    while(i<len(a)-1):
        #print x
        if (10**i)==x:
            print a[i]
            flag=1
            break
        elif x>(10**i) and x<(10**(i+1)):
            print a[i]
            flag=1
            break
        i=i+1

    if (i==len(a)-1 and flag==0 and x==(10**i)):
        print a[i]

number=int(input())
Number(number+1)

Please help as to how to handle large input values for the above as time limit got exceeded is coming for inputs close to 10^10000

4 Answers4

0

The simplest way to do this in pure python is to use len(number) where "number" has the required base.

GiovanH
  • 359
  • 2
  • 9
0

As shown above in the comments, math.log10 is not accurate enough for large numbers. Try a while loop:

n = 10 ** 10000 - 1
count = 0
while n > 0:
    n //= 10
    count += 1

print(count)

Output:

10000

Changing n to 10 ** 10000 outputs 10001 as expected.

EDIT: I found something very surprising (to me, at least):

len(str(n))

is actually EXTREMELY fast! I tested for numbers up to 10^1000000, and it finishes executing in a matter of seconds!

iz_
  • 15,923
  • 3
  • 25
  • 40
0

To the commenters saying that this is an integer, the data being discussed in this question would overflow an integer, and these numbers would have to be represented as a strings in memory due to their length.

miles_b
  • 335
  • 3
  • 10
0

OP has stated in a comment that his problem is he needs to take a numerical input in the form of a string, add 1 to it, and return the number of digits.

Adding 1 to a number will change the number of digits IF AND ONLY IF the string is composed completely of 9s. A simple test can achieve this. If it is all 9s, output the string length plus 1, otherwise output the unchanged string length.

num = input()
length = len(num)
if num == '9' * length: # checks if string is all 9's
    print(length + 1)
else:
    print(length)

By eliminating the need to convert to int and back, we save a lot of time. This code executes in fractions of a second.

iz_
  • 15,923
  • 3
  • 25
  • 40