WAP to calculate 1!+2!+3!+4!+5!
Objective
Write a C++ program to calculate the series sum: 1! + 2! + 3! + 4! + 5!
Algorithm / Approach
- Write a recursive
fact()function. - In
main(), use aforloop from 1 to 5. - Inside the loop, add the result of the function to a running total:
sum = sum + fact(i). - Print the sum.
main.cpp
#include<iostream>
using namespace std;
int fact(int);
int main( ){
int i, sum=0;
for(i=1; i<=5; i++){
sum = sum+fact(i);
}
cout<<"SUM = "<< sum;
return 0;
}
int fact(int x){
if(x==0 || x==1){
return 1;
}
else{
return x*fact(x-1);
}
}
Expected Output
SUM = 153
Explanation of the Program
- By placing a function call inside a loop, we can quickly generate complex mathematical series.
- In this case, the loop counts from 1 to 5, and the function handles calculating the factorial for each individual step.
Complexity
Time Complexity
O(n^2) - The loop runs O(n) times, and each factorial calculation takes O(n) time.
Space Complexity
O(n) - For the recursive stack.