patterncppMinor
Effectively calculate the result of geometric series
Viewed 0 times
resulttheeffectivelycalculateseriesgeometric
Problem
Given \$f(n) = 1 + x + x^2 + x^3 + \ldots + x^n\$ and the fact that computers take more time when multiplying two numbers than when adding, how can we work out the result with greater efficiency?
#include
using namespace std;
double powerWithIntExponent(double base, int exponent)
{
if(exponent == 0)
return 1;
if (exponent == 1)
return base;
double result = powerWithIntExponent(base, exponent >> 1);
result *= result;
if ((exponent & 0x1) == 1) {
result *= base;
}
return result;
}
double func(double x, int n)
{
if (x == 0) return 1;
if (x == 1) return n+1;
double sum = 0;
double x_n = 0;
x_n = powerWithIntExponent(x, n+1);// the Geometric series start from x^0
sum = (1-x_n)/(1-x);
return sum;
}
int main(int argc, const char * argv[])
{
double result = func(2, 2);
cout<<result<<endl;
return 0;
}Solution
Instead of using a recursive algorithm (which might overflow the stack for large exponents) and calculating the power yourself, use the
Now a few minor remarks about your original code: be sure to be more consistent with your coding style. For example:
vs.
Personally, I'd always either write it on one line as in the second example or if there is a newline, I'd always add braces. For reasons see Apple's
(Same with whitespace: there should be a space after the
Consistency would also be nice here:
Either use
pow function which is likely pretty optimized.#include
#include
using namespace std;
double func(double x, int n)
{
double x_n;
x_n = pow(x, n+1);
return (1-x_n)/(1-x);
}
int main(int argc, const char * argv[])
{
double result = func(2, 2);
cout<<result<<endl;
return 0;
}Now a few minor remarks about your original code: be sure to be more consistent with your coding style. For example:
if(exponent == 0)
return 1;
if (exponent == 1)
return base;vs.
if (x == 0) return 1;
if (x == 1) return n+1;Personally, I'd always either write it on one line as in the second example or if there is a newline, I'd always add braces. For reasons see Apple's
goto fail;. But it's actually a personal preference, you don't need to do it that way but I highly recommend that you chose one style and stick to it.(Same with whitespace: there should be a space after the
if in if(exponent == 0))Consistency would also be nice here:
if ((exponent & 0x1) == 1)Either use
0x1 both times or 1 both times. I feel that mixing these isn't a good idea.Code Snippets
#include <iostream>
#include <cmath>
using namespace std;
double func(double x, int n)
{
double x_n;
x_n = pow(x, n+1);
return (1-x_n)/(1-x);
}
int main(int argc, const char * argv[])
{
double result = func(2, 2);
cout<<result<<endl;
return 0;
}if(exponent == 0)
return 1;
if (exponent == 1)
return base;if (x == 0) return 1;
if (x == 1) return n+1;if ((exponent & 0x1) == 1)Context
StackExchange Code Review Q#62716, answer score: 6
Revisions (0)
No revisions yet.