How to resolve the algorithm Factorial step by step in the COBOL programming language
Published on 12 May 2024 09:40 PM
How to resolve the algorithm Factorial step by step in the COBOL programming language
Table of Contents
Problem Statement
Write a function to return the factorial of a number. Solutions can be iterative or recursive. Support for trapping negative n errors is optional.
Let's start with the solution:
Step by Step solution about How to resolve the algorithm Factorial step by step in the COBOL programming language
Source code in the cobol programming language
MOVE FUNCTION FACTORIAL(num) TO result
IDENTIFICATION DIVISION.
FUNCTION-ID. factorial_iterative.
DATA DIVISION.
LOCAL-STORAGE SECTION.
01 i PIC 9(38).
LINKAGE SECTION.
01 n PIC 9(38).
01 ret PIC 9(38).
PROCEDURE DIVISION USING BY VALUE n RETURNING ret.
MOVE 1 TO ret
PERFORM VARYING i FROM 2 BY 1 UNTIL n < i
MULTIPLY i BY ret
END-PERFORM
GOBACK.
END FUNCTION factorial_iterative.
IDENTIFICATION DIVISION.
FUNCTION-ID. factorial_recursive.
DATA DIVISION.
LOCAL-STORAGE SECTION.
01 prev-n PIC 9(38).
LINKAGE SECTION.
01 n PIC 9(38).
01 ret PIC 9(38).
PROCEDURE DIVISION USING BY VALUE n RETURNING ret.
IF n = 0
MOVE 1 TO ret
ELSE
SUBTRACT 1 FROM n GIVING prev-n
MULTIPLY n BY factorial_recursive(prev-n) GIVING ret
END-IF
GOBACK.
END FUNCTION factorial_recursive.
IDENTIFICATION DIVISION.
PROGRAM-ID. factorial_test.
ENVIRONMENT DIVISION.
CONFIGURATION SECTION.
REPOSITORY.
FUNCTION factorial_iterative
FUNCTION factorial_recursive.
DATA DIVISION.
LOCAL-STORAGE SECTION.
01 i PIC 9(38).
PROCEDURE DIVISION.
DISPLAY
"i = "
WITH NO ADVANCING
END-DISPLAY.
ACCEPT i END-ACCEPT.
DISPLAY SPACE END-DISPLAY.
DISPLAY
"factorial_iterative(i) = "
factorial_iterative(i)
END-DISPLAY.
DISPLAY
"factorial_recursive(i) = "
factorial_recursive(i)
END-DISPLAY.
GOBACK.
END PROGRAM factorial_test.
You may also check:How to resolve the algorithm Metronome step by step in the AutoHotkey programming language
You may also check:How to resolve the algorithm Polynomial long division step by step in the Smalltalk programming language
You may also check:How to resolve the algorithm Address of a variable step by step in the ERRE programming language
You may also check:How to resolve the algorithm Convert decimal number to rational step by step in the Go programming language
You may also check:How to resolve the algorithm Catamorphism step by step in the Tcl programming language