0

I wrote some simple code in Python, JavaScript and C. I found that the Python and JavaScript results are the same, but C gives me another -wrong- result and I can't understand what is the error.

C code:

int fact(int n){
    if(n==1){
        return 1;
    }else{
        return (n*fact(n-1));
    }
}

int main(void){
    printf("%i \n",fact(13));
}

JS code:

function fact(n){
    if (n==1){
        return (1);
    }else{
        return (n*fact(n-1));
    }
}

console.log(fact(13));

Python code:

def fact(n):
    if(n == 0):
        return 1
    else:
        return n * fact(n - 1)

print(fact(13))

Can you explain?

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
Kevin Omar
  • 127
  • 9
  • 2
    Never done any C, but I bet that the desired result of 6227020800 is just too big [to fit in an int](https://stackoverflow.com/questions/11438794/is-the-size-of-c-int-2-bytes-or-4-bytes) – CertainPerformance May 27 '19 at 23:53
  • thank you for your speedy reply but what can i use for too big intgers? – Kevin Omar May 27 '19 at 23:57
  • 2
    https://en.wikipedia.org/wiki/C_data_types makes me think maybe `unsigned long long int` – CertainPerformance May 27 '19 at 23:59
  • 1
    Use `long long` [64 bit wide] instead of `int` [32 bit wide]. Also, (e.g.) `printf("%lld\n",num);` instead of `printf("%d\n",num);` – Craig Estey May 28 '19 at 00:01
  • 3
    `unsigned long long` would be the best option, but bear in mind it's limited as well and it won't be able to hold values past ~`fact(20)`. – CristiFati May 28 '19 at 00:05
  • Also note that your python version works for n as low as 0, but your C and javascript versions only work down to 1 because they're checking `n == 1` instead of `n == 0`. `n == 0` is preferred, since it alllows your function to work for all non-negative integers (until it overflows). (`0!` is well-defined and its value is `1`) – Tom Karzes May 28 '19 at 00:47
  • @CristiFati then fact(21) give wrong result, what should we use to fix that? – Kevin Omar May 30 '19 at 22:21

1 Answers1

1

Being interpreted languages, they (probably) automatically choose the data type for variables according to the size of the data.

However, in C you specified that "int" has to be used - and it is way too small to hold 13!

If you switch "int" for "unsigned long long int" (yes, use "long" twice), then your program will return proper results for a longer time, until it fails again - exceeding the size of 64-bits.

virolino
  • 2,073
  • 5
  • 21