简体   繁体   中英

OCaml fatorial is 0

I want to have a code that calculates the Narayana numbers. https://en.wikipedia.org/wiki/Narayana_number

However, it starts to present '0' for numbers over 20.

What might be failing?

let rec factorial n =
    if n <= 1 then 1
    else factorial (n-1) * n;;

factorial 21 overflows and returns an incorrect result. The max_int value of on my 64bit setup is 4611686018427387903, which is just between 20! and 21!.

The to get around this you can avoid actually calculating the value of n! (or k!) ub binomial_coeff . Instead calculate more complex values. For instance, instead of n!/k! , you can use (k+1)*(k+2)*...*n .

You missed a piece of code, that is factorial (n) as numerator:

let binomial_coeff (n:int) (k:int) =
    if k = 0 || k = n then 1
    else factorial (n) / (factorial (k) * factorial (n-k));;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM