Skip to main content

FACTOR.F95

	PROGRAM FACTOR
!
!  Purpose: to display the factorial of a number on the screen
!
	IMPLICIT NONE
	INTEGER:: N	! Integer to be entered on the keyboard 
	INTEGER:: FACT	! Integer factorial function
!
	WRITE(*,10,ADVANCE='NO')
   10	FORMAT('Enter the integer you want to calculate the factorial of: ')
	READ(*,*)N
!
!  Check the input
	IF(N < 0)THEN
	   WRITE(*,11)
	   STOP
	END IF
   11	FORMAT('N should not be negative.')
!
!  Print the factorial. (Note that there will be an overflow is N is too big.)
	WRITE(*,20)FACT(N)
   20	FORMAT('The factorial is: ',I12)
!
	END PROGRAM FACTOR
!
	INTEGER FUNCTION FACT(N)
!
!  Calculate the factorial of the integer N. Calls for too large values of N
!  produce an integer overflow. N is assumed to be non-negative.
!
	IMPLICIT NONE
	INTEGER:: N,I
!
	IF(N == 0)THEN
	   FACT=1
	ELSE
	   FACT=1
	   DO I=1,N
	      FACT=I*FACT
	   END DO
	END IF
!
	RETURN
	END FUNCTION FACT