(A) Problem Statement:
Write a program to calculate factorial
of a given positive integer by using iterative and recursive
methods. Find the time and space complexity.
(B) Input and Output :
(i) The input for the given problem is any positive integer
Like 10
The expected output for the input 10 is 3628800.
(ii) The expected output for the input 5 is 120.
(C) Examples :
(i) 10! = 1* 2*3*4*5*6*7*8*9*10 = 3628800.
(ii) 5! = 1*2*3*4*5 = 120.
(D)Algorithm :
Step 1: Start
Step 2: Read the positive integer n and initialize fact variable
to 1.
Step 3:
(a) iterative method:
(i) Repeatedly calculate the statement for I values
from 1 to n.
fact = fact*I;
(ii) print the factorial of n which is fact.
(b) Recursive method:
(i) Repeatedly call the factn function for n until n
value is 1.
(ii) The factn function contains the statement
Fact = n*factn(n-1)
(iii) Print the factorial which is returned by factn
function.
Step 4: Stop
(E) Program :
/* Write C programs that use both recursive and non-recursive functions To find the factorial of a given positive integer.*/
#include
#include
#include
long int recr_factorial(long int n);
long int iter_factorial(long int n);
void main()
{
long int n,i;
clrscr();
do
{
printf("Enter the positive number: "); //read the positive integer
scanf("%ld",&n);
}while(n<0);
if(n==0)
printf("Factorial of 0 is 1\n"); //factorial of 0 is 1
else
{ //find factorial by calling 2 functions
printf("Factorial of %ld Using Recursive Function is %ld\n",n,recr_factorial(n));
printf("Factorial of %ld Using Non-Recursive Function is %ld\n",n,iter_factorial(n));
}
getch();
}
/* Recursive Function*/
long int recr_factorial(long int n) {
return n>=1 ? n * recr_factorial(n-1) : 1; //recursively calling function
}
/* Non-Recursive Function*/
long int iter_factorial(long int n) {
long int accu = 1; //intialize accu to 1
int i;
for(i = 1; i <= n; i++) { //repetedly multiply i withaccu
accu *= i;
}
return accu; //return factorial
}
(F) Testing :
S.No
Aspect to be tested
Expected result
1
Positive integer = 5
120
Successful
2
Positive integer = -2
Fails
(Enter positive integer)
3
Positive integer = 20
Wrong result
(Due to Out of range )
(G) Limitations :
(i) In this program the positive n is taken as long int . the range
of long int is 2,147,483,647.So, it can calculate up to factorial
of 19.
No comments:
Post a Comment