Beliavsky / FortranTip

Short instructional Fortran codes associated with Twitter @FortranTip
https://zmoon.github.io/FortranTipBrowser/
The Unlicense
64 stars 14 forks source link

The missing factorial function #19

Closed urbanjost closed 2 years ago

urbanjost commented 2 years ago

Why does Fortran not have a factorial function?

It does, as for positive whole values of X the Gamma function simplifies to the factorial function for (X-1). That is,

x! == gamma(x+1)
program testit
use, intrinsic :: iso_fortran_env, only : wp=>real64
integer,parameter :: n(*)=[0,1,5,11,170]
integer :: j

   do j=1,size(n)
      write(*,'(*(g0,1x))')'factorial of', n(j),' is ', &
       & product([(real(i,kind=wp),i=1,n(j))]),         &
       & ' or ',                                        &
       & gamma(real(n(j)+1,kind=wp))
   enddo

end program testit
Beliavsky commented 2 years ago

Posted, thanks!