Program which calculate a sum of series [C++]

1 reply · 7K views · last reply
nodek
Messages
4
Reaction score
0
Hi ! I`m trying to write a program which will calculate the sum:
[tex]x+(x+x^{2})+(x+x^{2}+x{3})+...[/tex]

Homework Statement



Hi ! I`m trying to write a program which will calculate the sum:
[tex]x+(x+x^{2})+(x+x^{2}+x{3})+...[/tex]
I want the user to type in number of terms [tex]n[/tex], as well as a value of x. Here is my attempt:
#include <iostream>
#include <string>
#include <cmath>

using namespace std;int main() {

int n, x, sum=0 ;
count<<"Enter the value for x: "<<endl;
cin>>x;

count<<"Enter the number of terms : " <<endl;
cin>>n;

for( int i =1; 1<=n; i++) {
for (int j=1; j<=i; j++)
{
sum+=pow(x, i);
}
}

count<<"The sum is"<<sum<<endl;
return 0;

cin.get();
cin.get();
}Is it a good way of doing that? One of mistakes that I made was : "error C2668: 'pow' : ambiguous call to overloaded function". What should I do about it?

Regards
Nodek
 
Why do you use ints for everything? What are types of expected arguments of pow()?

Also, your approach is about as inefficient as possible. Note that

[tex]x + (x + x^2) + (x + x^2 + x^3) = 3x + 2x^2 + x^3[/tex]

and using Horner scheme for polynomial calculation:

[tex]3x + 2x^2 + x^3 = x(3+x(2+x))[/tex]

That means you don't need pow() function - which is numerically heavy - at all.