Tuesday, December 27, 2011

Project Euler Problem 34 Solution

Problem Statement
145 is a curious number, as 1! + 4! + 5! = 1 + 24 + 120 = 145.
Find the sum of all numbers which are equal to the sum of the factorial of their digits.
Note: as 1! = 1 and 2! = 2 are not sums they are not included.
Solution (Bruteforce)

#include <iostream>
#include <ctime>

using namespace std;

#define sz 362880
long f[10];

long test( long n ){
 long sum = 0;
 while( n ){
  sum += f[n % 10];
  n /= 10;
 }

 return sum;
}

int main(){
 long i,j,k,l,cnt = 0,ans = 0;
 double st,en;

 st = clock();

 f[0] = 1;
 f[1] = 1;
 for( i = 2; i <= 9; i++ )
  f[i] = f[i-1] * i;

 for( i = 3; i <= sz; i++ ){
  if( test(i) == i){
   ans += i;
   cnt++;
   printf("%ld\n",i);
  }
 }

 printf("%ld\n",cnt);
 printf("ANS : %ld\n",ans);

 en = clock();

 printf("Time required : %lf\n",(en - st)/CLOCKS_PER_SEC);

 return 0;
}

1 comment:

novergary123 said...

So what would be the pseudocode for this?

Post a Comment