Project Euler Problem 30

//

I hadn't solved a Project Euler problem in quite some time, so I figured I'd sit down and bang one out. Problem 30 was pretty straight forward.

Surprisingly there are only three numbers that can be written as the sum of fourth powers of their digits:

1634 = 14 + 64 + 34 + 44
8208 = 84 + 24 + 04 + 84
9474 = 94 + 44 + 74 + 44
As 1 = 14 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.

  1. #!/usr/bin/perl -w
  2.  
  3. use strict;
  4.  
  5. # precompute our powers
  6. my $pows;
  7. for(my $i = 0; $i < 10; $i++) {
  8.         $pows->{$i} = $i**5;
  9. }
  10.  
  11. my @result  = ();
  12. my $i       = 2;
  13. while(1) {
  14.     my @digits = split(//, $i);
  15.     my $sum = 0;
  16.     foreach my $digit (@digits) {
  17.         $sum += $pows->{$digit};
  18.     }
  19.     if($sum == $i) {
  20.         push(@result, $i);
  21.         print join(",", @result) ." = " . eval(join('+', @result)) . "\n";
  22.     }
  23.     $i   +=1;
  24.     $sum = 0;
  25. }