C Program to calculate 1/1!+2/2!+3^2/3!+4^3/4!+5^4/5!+6^5/6!
Objective
Write a C program to calculate a complex mathematical series using multiple functions.
Algorithm / Approach
- Create a
fact()function for factorials. - Create a
power(x, y)function to calculate exponents. - In
main(), run a loopifrom 0 to 6. - Inside the loop, calculate the term:
sum = sum + power(i, i-1) / fact(i). - Because division can result in decimals, ensure variables handling the result are declared as
float.
main.c
#include<stdio.h>
int fact(int);
float power(int,int);
int main( ){
int i;
float sum;
for(i=0; i<=6; i++){
sum = sum+power(i,i-1)/fact(i);
}
printf("Sum = %f\n",sum);
return 0;
}
int fact(int x){
if(x==0 || x==1){
return 1;
}
else{
return x*fact(x-1);
}
}
float power(int x, int y){
int j, result=1;
for(j=1; j<=y; j++){
result = x*result;
}
return result;
}
Expected Output
Sum = 22.174999
Explanation of the Program
- When mathematical formulas become complex, burying them in a massive single block of code makes them impossible to read or debug.
- By offloading the heavy lifting to smaller, dedicated functions (
factandpower), the main loop equation becomes clean and easy to understand.
Complexity
Time Complexity
O(n^2)
Space Complexity
O(n)