i want the source code (algorithm) of this with just simple tools (like if,for and while without void or external functions)
here is mine that is incorrect:
#include <iostream>
using namespace std;
int main()
{
int j=1,i=1,power=1;
double q,sum=0,fact,r=1,x;
cout <<"Enter a NUm"<<endl;
cin>>x;
while (j<=10)
{
while(i<=j)
{
power*=x;
++i;
if (i%2==0)
power*=(-1);
for (power=1,q=1;q>10;q+=2)
{
fact=q*(q-1);
r=fact*r;
if (fact==0)
{
r=1;
}
}
}
sum=(power/r)+sum;
++j;
}
cout <<"\n\n\n\t\t"<<sum;
cin.ignore();
cin.get();
}
double x;
cin >> x;
double term = x;// 1st term
double sum = term;// 1st term summed
Then, for each remaining term:
1 2
term *= -x/(double)j;
sum += term;
@darkmaster: I think your function would work, but OP asked for a solution without calls to "external" functions. This may include both pow() and faculty().
Those two lines find the jth term and add it to the sum.
You need to sum 10 terms right?
The 1st term is included by the initial values for term and sum.
You need to add the other 9 terms, for j=2 though j=10.
1 2 3 4 5
for( j=2; j<=10; j++)
{
term *= -x/(double)j;// builds up value of (x^j)/j!
sum += term;
}
That works by using the ratio of successive terms.
int num;
cin >> num;
double result = num;
for (int i = 2; i <= 10; i ++) {
int power = 1;
// Get the power
for (int j = 1; j <= i; j ++)
power *= num;
double fact = 1;
// Get the factorial
for (int j = 1; j <= i; j ++)
fact *= i;
// If x (i) is even, we subtract the next terms
if (i % 2 == 0)
result -= (power / fact);
// Otherwise, we add
else
result += (power / fact);
}
Look at the ratio of successive terms.
Example:
Let t3 = x^3/3! = third term in the series
then t4 = -(x^4/4!) = fourth term in the series
Notice that t4/t3 = -x/4
So you can find t4 from t3 like this:
t4 = -(x/4)*t3;
Generally:
tn+1 = -(x/n)*tn;
There is no need to find x^n or n! for each term.
One class I wish I would have taken was discrete math. I love math and logic and go figure there is a class that has both and I never had it. I don't see patterns in numbers like I should and it hinders my abilities as a programmer since it's all about patterns.
#include <iostream>
using namespace std;
int main()
{
long float n,x,sum=0,t=-1;
cout<<"Enter a Number : ";
cin>>x;
cout<<"\n\n\n"<<"Press Enter to calculate x- (x^2/2!) + (x^3/3!)- ... + (x^9/9!) - (x^10/10!)";
cin.ignore();
cin.get();
for(n=1;n<=10;n++)
{
t=(-x/n)*t;
sum=t+sum;
cout<< "\t\n"<<"t"<<n<<"="<<t<<"\t\n";
}
cout<<"\n\n\n\t"<< "SUM of them is = " <<sum;
cin.ignore();
cin.get();
}