Search code examples
cfactorial

Program in C , working with 3 digits but not working with 5 digits


145 = sum of 1! + 4! + 5!. I need to write a program in C, that finds the 5 digit numbers that have this property.

I have written the code successfully for the 3 digits. I used the same code for 5 digits, but it cant find any number.

I would like to help me with my solution, in order for me to see where am I wrong.

#include <stdio.h>

int factorial(int n);

main() {
    int pin[5];

    int q = 1;
    int w = 0;
    int e = 0;
    int r = 0;
    int t = 0;

    int result = 0;

    int sum = 0;

    for (q = 1; q <= 9; q++) {
        for (w = 0; w <= 9; w++) {
            for (e = 0; e <= 9; e++) {
                for (r = 0; r <= 9; r++) {
                    for (t = 0; t <= 9; t++) {
                        pin[0] = q;
                        pin[1] = w;
                        pin[2] = e;
                        pin[3] = r;
                        pin[4] = t;

                        int factq = factorial(q);
                        int factw = factorial(w);
                        int facte = factorial(e);
                        int factr = factorial(r);                                                                       
                        int factt = factorial(t);

                        sum = factq + factw + facte + factr + factt;                
                        result = 10000 * q + 1000 * w + 100 * e + 10 * r + t * 1;

                        if (sum == result)
                            printf("ok");
                    }
                }
            }
        }
    }
}

int factorial(int n) {
    int y;
    if (n == 1) {
        y = 1;
    } else if (n == 0)
        y = 0;
    else {
        y = n * factorial(n - 1);
        return y;
    }
}

Solution

  • Your factorial function doesn't return a value in all cases:

    int factorial (int n) {
        int y;
        if (n==1) {
            y = 1;
        }
        else 
            if (n==0)
                y = 0;
            else {
                y = n * factorial(n-1);
                return y;
            }
    }
    

    It only returns a value when it makes a recursive call. The base cases don't return anything. Failing to return a value from a function and then attempting to use that value invokes undefined behavior.

    Move the return statement to the bottom of the function so it gets called in all cases. Also the value of 0! is 1, not 0.

    int factorial (int n) {
        int y;
        if (n<=1)
            y = 1;
        else 
            y = n * factorial(n-1);
        return y;
    }
    

    Also, when you find the target value you probably want to print it:

    printf("ok: %d\n", result);