# Recursion function

1. Oct 12, 2015

### Sue Parks

I understand that FORTRAN 90 has a built-it recursion function. How could I implement this function without using the built in recursion function?

Code (Fortran):

PROGRAM RECURSIVE_FACT
IMPLICIT NONE
INTEGER, PARAMETER :: M = 100
DOUBLE PRECISION :: fact
INTEGER :: I

PRINT *, factorial (N)
CONTINUE
RECURSIVE FUNCTION Factorial(n)  RESULT(Fact)

IMPLICIT NONE
INTEGER :: Fact
INTEGER, INTENT(IN) :: n

IF (n == 0) THEN
Fact = 1
ELSE
Fact = n * Factorial(n-1)
END IF

END FUNCTION Factorial

END PROGRAM RECURSIVE_FACT

Last edited by a moderator: Oct 12, 2015
2. Oct 12, 2015

### Staff: Mentor

Don't you need a return statement following the IF statement in your Factorial function?

Code (Fortran):

IF ( n == 0 ) THEN
Fact =1
ELSE
Fact = n * Factorial( n - 1 )
ENDIF

RETURN Fact

END FUNCTION Factorial

3. Oct 12, 2015

### Sue Parks

WHE I FIRST TRIED YOUR SUGGESTION (RETURN STATEMENT), IT RETURNED 0. Now I have multiple errors: (Here is one). Do I HAVE to use the recursive function??????
RECURSIVE_FACTORIAL.f90:20.26:
Function 'factorial' at (1) has no IMPLICIT type

Code (Fortran):

IMPLICIT NONE
INTEGER, PARAMETER :: M = 100
DOUBLE PRECISION :: fact
INTEGER :: I,N

PRINT *, factorial (N)
CONTINUE
RECURSIVE FUNCTION Factorial(n)  RESULT(Fact)   !! CAN I MAKE MY OWN FUNCTION HERE???????

IMPLICIT NONE
DOUBLE PRECISION :: Fact
INTEGER, INTENT(IN) :: n

IF (n == 0) THEN
Fact = 1
ELSE
Fact = n * Factorial(n-1)
END IF
RETURN FACT

END FUNCTION Factorial

END PROGRAM RECURSIVE_FACTORIAL

4. Oct 12, 2015

### gsal

the word CONTINUE , should really be CONTAINS.

5. Oct 12, 2015

### gsal

Also, there was another thread where we discussed the fact that the factorial can get really large and may end up not fitting even in a double precision number...

6. Oct 12, 2015

### Staff: Mentor

Or you could write the program like this:
Code (Fortran):

PROGRAM RECURSIVE_FACT
IMPLICIT NONE
INTEGER, PARAMETER :: M = 100
DOUBLE PRECISION :: fact
INTEGER :: I

PRINT *, factorial (N)
END PROGRAM RECURSIVE_FACT

RECURSIVE FUNCTION Factorial(n)  RESULT(Fact)
IMPLICIT NONE
INTEGER :: Fact
INTEGER, INTENT(IN) :: n

IF (n == 0) THEN
Fact = 1
ELSE
Fact = n * Factorial(n-1)
END IF
END FUNCTION Factorial