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

  • Context: Comp Sci 
  • Thread starter Thread starter nodek
  • Start date Start date
  • Tags Tags
    Program Series Sum
Click For Summary
SUMMARY

The discussion centers on a C++ program designed to calculate the sum of a series defined as x + (x + x²) + (x + x² + x³). The user is prompted to input the number of terms (n) and a value for x. The initial implementation encounters an error due to the ambiguous call to the overloaded function 'pow'. A more efficient approach is suggested, utilizing the Horner scheme for polynomial evaluation, which eliminates the need for the 'pow' function and improves performance.

PREREQUISITES
  • Understanding of C++ syntax and structure
  • Familiarity with the 'pow' function in C++
  • Knowledge of polynomial evaluation techniques
  • Basic concepts of loops and control structures in programming
NEXT STEPS
  • Implement the Horner scheme for polynomial calculation in C++
  • Explore the performance implications of using 'pow' versus direct multiplication
  • Learn about function overloading and how to resolve ambiguous calls in C++
  • Investigate optimization techniques for iterative algorithms in C++
USEFUL FOR

C++ developers, computer science students, and anyone interested in optimizing polynomial calculations in programming.

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 ;
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
 
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 ·
Replies
3
Views
1K
  • · Replies 2 ·
Replies
2
Views
3K
  • · Replies 2 ·
Replies
2
Views
2K
  • · Replies 24 ·
Replies
24
Views
2K
  • · Replies 3 ·
Replies
3
Views
2K
  • · Replies 8 ·
Replies
8
Views
2K
  • · Replies 7 ·
Replies
7
Views
2K
  • · Replies 23 ·
Replies
23
Views
3K
  • · Replies 3 ·
Replies
3
Views
2K
  • · Replies 13 ·
Replies
13
Views
2K