Project Euler Problem 30
Digit fifth powers.
Surprisingly there are only three numbers that can be written as the sum of fourth powers of their digits:
1634 = 1^4 + 6^4 + 3^4 + 4^4 8208 = 8^4 + 2^4 + 0^4 + 8^4 9474 = 9^4 + 4^4 + 7^4 + 4^4
As 1 = 1^4 is not a sum it is not included.
The sum of these numbers is 1634 + 8208 + 9474 = 19316.
Find the sum of all the numbers that can be written as the sum of fifth powers of their digits.
Link to original description
Source code examples on Github
A number x with n digits and the sum s of the fifth powers of its digits satisfy x>=10^(n-1) and s<=n^5 respectively.
Thus it must be 10^(n-1)<=n^5, which implies 1<=n<=6, and x<=6*9^5.
Python version
1 2 3 4 5 6 7 8 9 10 11 12 13 | #!/usr/bin/python def power_of_digits(n, p): s = 0 while n > 0: d = n % 10 n = n / 10 s = s + pow(d, p) return s print sum(n for n in xrange(2, 6*9**5) if power_of_digits(n, 5) == n) |
Perl version
1 2 3 4 5 6 7 8 | #!/usr/bin/perl -l use strict; use warnings; use List::Util qw/sum/; print sum grep { $_ == sum map $_**5, /./g } 2..6*9**5; |
Erlang version
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | #!/usr/bin/env escript %% -*- erlang -*- %%! -smp enable -sname p30 % vim:syn=erlang -mode(compile). main(_) -> Answer = lists:sum(lists:filter(fun(N)-> sump(N,10,0) == N end, lists:seq(2,6*p5(9)))), io:format("Answer ~p ~n", [Answer]). p5(D) -> D*D*D*D*D. sump(0,_,A) -> A; sump(N,B,A) when N < B -> A+p5(N); sump(N,B,A) -> sump(N div B, B, A + p5(N rem B)). |