Compute binomial coefficient C(n,r) = n! / (r! * (n-r)!)
Calculates “n choose r” using iterative algorithm to avoid factorial overflow for large numbers. Uses int64 to handle large combinatorial values that overflow int32.
| Type | Intent | Optional | Attributes | Name | ||
|---|---|---|---|---|---|---|
| integer(kind=default_int), | intent(in) | :: | n |
Total number of items |
||
| integer(kind=default_int), | intent(in) | :: | r |
Number of items to choose |
Binomial coefficient result
| Type | Visibility | Attributes | Name | Initial | |||
|---|---|---|---|---|---|---|---|
| integer(kind=default_int), | private | :: | i |
Loop counter |
pure function binomial(n, r) result(c) !! Compute binomial coefficient C(n,r) = n! / (r! * (n-r)!) !! !! Calculates "n choose r" using iterative algorithm to avoid !! factorial overflow for large numbers. !! Uses int64 to handle large combinatorial values that overflow int32. integer(default_int), intent(in) :: n !! Total number of items integer(default_int), intent(in) :: r !! Number of items to choose integer(int64) :: c !! Binomial coefficient result integer(default_int) :: i !! Loop counter if (r == 0 .or. r == n) then c = 1_int64 else if (r > n) then c = 0_int64 else c = 1_int64 do i = 1, r c = c*int(n - i + 1, int64)/int(i, int64) end do end if end function binomial