Dismiss Notice
Join Physics Forums Today!
The friendliest, high quality science and math community on the planet! Everyone who loves science is here!

Factorial fortran 90

  1. May 29, 2015 #1
    Code (Text):

    program factorial
      implicit none
      integer::fact,i,n
      print*,'enter the value of n'
      read*,n
      fact=1
      do i=1,n
      fact=fact*i
      end do

      print*,'factorial is ',fact
    end program
     
    when input n largest number then answer is incorrect. how to solve
     
  2. jcsd
  3. May 29, 2015 #2

    berkeman

    User Avatar

    Staff: Mentor

    Show us what you get for the first few possibilities for n:

    1
    2
    3
    4
    5
    6

    etc.
     
  4. May 29, 2015 #3

    FactChecker

    User Avatar
    Science Advisor
    Gold Member

    Your code looks good to me. When you say the answer is incorrect for "the largest number", don't forget that fact will be larger than the largest allowable integer in that case. The program will either abort or give an incorrect answer. You can only input values of n that will not make n! too large for the integer fact.
     
  5. Jun 2, 2015 #4

    Zondrina

    User Avatar
    Homework Helper

    There are implementations of the factorial function that allow the computation of factorials beyond 20!.

    The implementations are much more difficult to write, but if you want to get around the storage limits, you have to be a bit more clever.
     
  6. Jun 2, 2015 #5
    You need to start using Fortran90 intrinsic functions that allow for requesting more storage in a platform compatible manner, I am talking about functions like "selected_int_kind"; in my laptop, I was able to go as high as 18. Needless to say, the factorial function is a nice textbook exercise to show another Fortran90 feature: recursive attribute.

    Code (Text):

    program torial
        implicit none
       
        integer, parameter :: IK = selected_int_kind(18)
        integer(IK) :: i
         
        write(*,'(A,$)') 'Number? : '
        read(*,*) i
        write(*,*) 'Factorial is ',factorial(i)

    contains

        recursive function factorial( n ) result (f)
            integer(IK) :: f, n
           
            if( n == 1 ) then
              f = 1
            else
              f = n * factorial( n - 1_IK )
            end if
           
        end function factorial
       
    end program torial
     
    > a.exe
    Number? : 20
    Factorial is 2432902008176640000
     
  7. Jun 5, 2015 #6
    For large numbers may you don't need exact an integer. Try the same code with result as double or extended real (16 byte float number gives answer up to 4930!).
     
Know someone interested in this topic? Share this thread via Reddit, Google+, Twitter, or Facebook




Similar Discussions: Factorial fortran 90
  1. Fortran 90 (Replies: 7)

  2. Fortran 90 (Replies: 1)

  3. Fortran Factorials (Replies: 6)

  4. Fortran 90 (Replies: 1)

Loading...