Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

an algorithm to calculate factorial " x! = ? " in C

Why does my code work correctly only when 12>=a ??

int main()
{
    int a ,x = 1;
    scanf("%d", &a);
    
    while (1 < a){
        x = a * x;
        a = (a - 1);
        printf("\n %d", x);
    };

    printf("\n %d", x);
    return 0;
}

what i did is asking the pc to print the result of a*(a-1) in every line then it prints the final factorial result.
And yes , the result is correct but not in all cases (from 13 and above it becomes wrong)

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

It is because factorial of 13 is greater than the holding capacity of int. So it cannot hold this value. try to use long variable here

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading