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

AI Thread Summary
The discussion focuses on creating a C++ program to calculate the sum of a series defined as x + (x + x^2) + (x + x^2 + x^3) based on user input for the number of terms n and the value of x. The initial code provided encounters an error related to the ambiguous call to the pow() function. A contributor suggests that using integers for all variables may not be appropriate and points out the inefficiency of the current approach. They recommend simplifying the calculation using the Horner scheme, which eliminates the need for the pow() function, thus improving performance. The conversation emphasizes optimizing the code for better efficiency and clarity.
nodek
Messages
4
Reaction score
0
Hi ! I`m trying to write a program which will calculate the sum:
x+(x+x^{2})+(x+x^{2}+x{3})+...

Homework Statement



Hi ! I`m trying to write a program which will calculate the sum:
x+(x+x^{2})+(x+x^{2}+x{3})+...
I want the user to type in number of terms n, 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 ;
cout<<"Enter the value for x: "<<endl;
cin>>x;

cout<<"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);
}
}

cout<<"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
 
Physics news on Phys.org
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

x + (x + x^2) + (x + x^2 + x^3) = 3x + 2x^2 + x^3

and using Horner scheme for polynomial calculation:

3x + 2x^2 + x^3 = x(3+x(2+x))

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

Similar threads

Replies
3
Views
1K
Replies
2
Views
3K
Replies
8
Views
1K
Replies
3
Views
2K
Replies
7
Views
2K
Replies
2
Views
2K
Replies
23
Views
3K
Replies
3
Views
1K
Back
Top