How to generate random numbers which do not include zeros?

Viewed 567

I am trying to create a program which finds multiplicative persistence in numbers which are randomized. This program, however, has to deal with large numbers (>10233). However, when I use random.randint(10**233, 10**400), I cannot help but notice that the vast majority of numbers contain a zero, which would result in 0 multiplicative persistence. In my algorithm, I am attempting to get rid of these numbers with the following approach:

def find_new_i():
    i = 10
    while "0" in str(i):
        i = random.randint(10**233,10**400)
    return i

However, this approach is really slow, and cannot generate numbers very quickly.

Has anyone got any ideas on a more efficient approach?

1 Answers

The odds to have a 0 in such a big number are very high, which is why the while loop is likely to repeat itself many times.

You are better of replacing any zeros with a random digit between 1 and 9.

def find_new_i():
    i = random.randint(10 ** 233, 10 ** 400)
    i = int(''.join(str(random.randint(1, 9)) if d == '0' else d for d in str(i)))
    return i

or if you don't mind all the zeros being replaced with the same random digit:

i = int(str(i).replace('0', str(random.randint(1, 9))))

At this stage it might make more sense to simply build the number "manually" (however this approach is about 4 times slower than the above, see the comments):

def find_new_i():
    return int(''.join(str(random.randint(1, 9))
               for _ in range(random.randint(233, 400))))
Related