# Project Euler #30: Digit Nth powers

# Project Euler #30: Digit Nth powers

+ 1 comment My sense was to do the following.

MIN = 2 MAX = 1000000 def compute(value): ans = sum(i for i in range(MIN, MAX) if i == power_digit_sum(value, i)) return str(ans) def power_digit_sum(value, n): return sum(int(c) ** value for c in str(n)) if __name__ == "__main__": value = int(input()) print(compute(value))

+ 1 comment My Approach - First find all possible numbers that a K-digit number could have for example I treated [1,2,3],[2,1,3],[1,3,2],[2,3,1],[3,1,2],[3,2,1] all as same and I find only one of them and not repeated numbers with same digits (using recursive appraoch) since what we are interested in only digits which constitute K-digit number . this way my algorithm is very fast and will also work if N (input) is even more than 6 .

+ 0 comments You can still use brute-force. Just do some experiments to determine lower and upper limit for i, then you will pass all cases.

def Digit_Nth_Powers(n,lower,upper): sumList = 0 for i in range(lower,upper): digits = list(map(int,str(i))) tempSum = 0 for j in digits: tempSum += j**n if i == tempSum: sumList += i return sumList if __name__ == '__main__': n = int(input()) # Lower and upper limit is determined by experiments for faster code execution if n == 3: lower,upper = [1*(10**2), 1*(10**3)] elif n == 4: lower,upper = [1*(10**3), 1*(10**4)] elif n == 5: lower,upper = [2*(10**3), 2*(10**5)] elif n == 6: lower,upper = [1*(10**5), 6*(10**5)] sumList = Digit_Nth_Powers(n,lower,upper) print(sumList)

+ 0 comments N = int(input()) c = [] for i in range(2, 10000000): cnt = 0 for j in str(i): cnt += int(j) ** N if cnt == i: c.append(cnt) print(c)

if you want to check for all numbers you can check the numbers in the list then you could simply check their sum for any N value. Just change the line "Print(c)" to print(sum(c)) Be sure to check this in your own ide as here it would give a TLE

+ 0 comments Try this

n=int(input()) print(sum([i for i in range(n**2,10**6) if i==sum(int(z)**n for z in str(i))]))

Sort 41 Discussions, By:

Please Login in order to post a comment