Implementing Recursion Function w/o FORTRAN 90 Built-in

  • Context: Fortran 
  • Thread starter Thread starter Sue Parks
  • Start date Start date
  • Tags Tags
    Function Recursion
Join the discussion
Ask a follow-up here, or get your own question answered by working scientists, mathematicians and engineers — people, not an autocomplete.
Real named experts · corrections over time · the nuance an AI answer skips
5 replies · 2K views
Sue Parks
Messages
38
Reaction score
0
I understand that FORTRAN 90 has a built-it recursion function. How could I implement this function without using the built in recursion function?

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:
on Phys.org
Don't you need a return statement following the IF statement in your Factorial function?

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

       RETURN Fact

END FUNCTION Factorial
 
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

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
 
the word CONTINUE , should really be CONTAINS.
 
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...
 
gsal said:
the word CONTINUE , should really be CONTAINS.
Or you could write the program like this:
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
 
  • Like
Likes   Reactions: bigfooted