Solution to Problem 30 on Project Euler


Improve your writing skills in 5 minutes a day with the Daily Writing Tips email newsletter.

The problem:

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.

My Solution

#include <stdio.h>
#include <math.h>

int main(){
  int i,a,b,c,d,e,f,n,sum;
  double number;
  sum =0;
  
  for (i=10;i<100;i++){
    a = i%10;
    b = i/10;
    number=pow(a,5)+pow(b,5);
    if ((int)number==i)
      sum+=(int)number;
  }

  for (i=100;i<1000;i++){
    n=i;
    a = n%10;
    n /= 10;
    b = n%10;
    n /= 10;
    c = n;
    number=pow(a,5)+pow(b,5)+pow(c,5);
    if ((int)number==i)
      sum+=(int)number;
  }

  for (i=1000;i<10000;i++){
    n=i;
    a = n % 10;
    n /= 10;
    b = n % 10;
    n /= 10;
    c = n % 10;
    n /= 10;
    d = n % 10;    
    number=pow(a,5)+pow(b,5)+pow(c,5)+pow(d,5);    
    if ((int)number==i)
      sum+=(int)number;
  }

  for (i=10000;i<100000;i++){
    n=i;
    a = n%10;
    n /= 10;
    b = n%10;
    n /= 10;
    c = n%10;
    n /= 10;
    d = n%10;
    n /= 10;
    e = n;
    number=pow(a,5)+pow(b,5)+pow(c,5)+pow(d,5)+pow(e,5);
    if ((int)number==i)
      sum+=(int)number;
  }

  for (i=100000;i<1000000;i++){
    n=i;
    a = n%10;
    n /= 10;
    b = n%10;
    n /= 10;
    c = n%10;
    n /= 10;
    d = n%10;
    n /= 10;
    e = n%10;
    n/=10;
    f=n;
    number=pow(a,5)+pow(b,5)+pow(c,5)+pow(d,5)+pow(e,5)+pow(f,5);
    if ((int)number==i)
      sum+=(int)number;
  }
  
  printf("%d\n",sum);  
  
return 0;
}

Leave a Reply

Your email address will not be published. Required fields are marked *