| 
  • If you are citizen of an European Union member nation, you may not use this service unless you are at least 16 years old.

  • You already know Dokkio is an AI-powered assistant to organize & manage your digital files & messages. Very soon, Dokkio will support Outlook as well as One Drive. Check it out today!

View
 

PE034_c

Page history last edited by Kenneth Finnegan 15 years, 7 months ago

// Solution to Project Euler #34

// sum of factorial of digits

#include <stdio.h>

#include <stdlib.h>

int factorial(int i);

main() {

    int i, sum=0;

    for (i=10; i<2540160; i++) { // 2540160 is the upper bound: 9! * 7

        int temp=i, tempsum=0;

        while (temp) {

            tempsum += factorial(temp%10);

            temp /= 10;

        }

        if (tempsum == i) {

            printf("Found: %d\n", i);

            sum += i;

        }

    }

    printf("\nSolution: %d\n", sum);

}

int factorial(int i) {

    if (i<0 || i>12) {

        fprintf(stderr, "Factorial input out of range\n");

        exit(EXIT_FAILURE);

    }

    static const int factorials[] = {1, 1, 2, 6, 24, 120, 720, 5040, 40320, 362880, 3628800, 39916800, 479001600};

    return factorials[i];

}

Comments (0)

You don't have permission to comment on this page.