Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why Is This Factorial Algorithm Not Accurate

Tags:

c

algorithm

Sorry I feel stupid asking this and am prepared to lose half of my points asking this but why does this algorithm not work? It works up to a point. After the number 13 the factorials are a little off. For instance the numbers do not entirely match in the hundreds thousands place and onward.

#include <stdio.h>

float factorial(unsigned int i) {

    if (i <= 1) {
        return 1;
    }
    return i * factorial(i - 1);
}

int  main() {
    int i = 13;
    printf("Factorial of %d is %f\n", i, factorial(i));
    return 0;
}

Here's the output:

Factorial of 13 is 6227020800.000000

Here is an example of inaccurate output:

Factorial of 14 is 87178289152.000000

The output for the number 14 should actually be this (from mathisfun.com)

14        87,178,291,200

I changed the return type to float to obtain more accurate output but I obtained this code for the most part from here: https://www.tutorialspoint.com/cprogramming/c_recursion.htm

EDIT: If I change to the return type to double the output is accurate up to 21.I am using the %Lf string formatter for the output in the printf function.

like image 892
user3808269 Avatar asked Nov 29 '22 22:11

user3808269


1 Answers

Simple. float cannot accurately store integers above 16777216 without loss of precision.

int is better than float. But try long long so you can properly store 19 digits.

like image 200
Paul Stelian Avatar answered Dec 05 '22 07:12

Paul Stelian