Hello
The factorial function crops up quite a lot would it be handy as an intrinsic function in ftn95? Just a thought.
program factorial_test
implicit none
! Store integers as 64-bit to handle very large numbers
integer(kind=4) :: n
integer(kind=4) :: fact_result
! Test the function with n = 20
n = 20
fact_result = factorial(n)
! Output the result
print *, 'Factorial of ', n, ' is: ', fact_result
contains
recursive function factorial(n) result(fact)
integer(kind=4) :: n
integer(kind=4) :: fact
! Check for negative or zero values
if (n < 0) then
print *, 'Error: Factorial is not defined for negative numbers.'
fact = -1 ! Error code for negative input
else if (n == 0) then
fact = 1 ! Factorial of 0 is 1
else
fact = n * factorial(n - 1) ! Recursive case
end if
end function factorial
end program factorial_test
A quick code testing a large value.
Lester