Hello I have to calculate the next sum recursively :
S= 1! + 1/2! + 3! + 1/4! + 5! + 1/6! + ......+ 1/(2n)! + (2n+1)!
So I split that into 2 sums:
S1 = 1! + 3! + 5! + ..... + (2n+1)! ->> S(n - 1) + n!, if n is odd
S2 = 1/2! + 1/4! + 1/6! + ...... + 1/(2n)! ->> S(n - 1) + 1 / (n!), if n is even
And I have to choose the number, even or odd.
This is what I got so far :
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52
|
#include <iostream>
using namespace std;
int factorial (int n)
{
if (n==0)
return 1;
else
return n*factorial(n-1); //function for the factorial
}
float SumaPar (int n)
{
if (n==0)
return 0;
else
return SumaPar(n-1) + (1.0/factorial(n)); //function for the even numbers
}
float SumaImpar (int n)
{
if (n==0)
return 0;
else
return SumaImpar(n-1) + (factorial(n)); //function for the odd numbers
}
int main ()
{
int n;
float S=0;
cout<<"Introduceti n=";
cin>>n;
{
if (n%2==0)
{
S= (SumaImpar(n) + SumaPar(n)) - 1;
}
else
{
S= (SumaImpar(n) + SumaPar(n-1)) - 1 ;
}
}
cout<<"Suma este : "<<S;
system("pause");
}
|
All works fine, but....instead of my sum it gives me this :
S=1!+2!+3!+4!+......+n! + 1/2! + 1/3! + 1/4! + 1/5! + ..... + 1/(2n+1)!
Any help will be apreciated.