Powerful digit counts (Euler Problem 63)

Back to overview.

The 5-digit number, 16807=$7^5$, is also a fifth power. Similarly, the 9-digit number, 134217728=$8^9$, is a ninth power.

How many n-digit positive integers exist which are also an nth power?

In [1]:
def get_digit_count(n):
    if n < 10:
        return 1
    c = 0
    while n:
        n //= 10
        c += 1
    return c

assert(get_digit_count(0) == 1)
assert(get_digit_count(1) == 1)
assert(get_digit_count(33) == 2)
assert(get_digit_count(100) == 3)
In [2]:
def get_n_digit_positive_integers(n):
    r = []
    i = 1
    while True:
        if get_digit_count(i ** n) == n:
            r.append(i ** n)
        if get_digit_count(i ** n) > n:
            return r
        i += 1

s = sum([len(get_n_digit_positive_integers(n)) for n in range(1, 1000)])
print(s)
assert(s == 49)
49
In [ ]: