What to write for this C++ program?

mindless728

Distinguished
Jul 15, 2008
130
0
18,660
Code:
#include <math.h>

//using a 64bit int
unsigned long long factorial(int n) {
   unsigned long long r = 1;

   if(n <= 0)
      return 1;

   for(int i = 1; i < n; i++)
      r *= i;

   return r;
}

double sum(double x) {
   const double epsilon = 1e-20
   double sum = 1;
   int i = 2;
   double addVal = addVal = pow(x,(double)i)/factorial(i);

   while(addVal > epsilon) {
      sum += addVal;
      i++;
      addVal = addVal = pow(x,(double)i)/factorial(i);
   } 

   return sum;
}
 

Zenthar

Distinguished
Dec 31, 2007
250
0
18,960
The factorial() function could be shortened a bit:
Code:
//using a 64bit int
unsigned long long factorial(int n) {
   unsigned long long r = 1;

   while(n > 1)
      r *= n--;

   return r;
}
And for the sum() function, I would use the #defined constant instead of defining it yourself.
Code:
#include <math.h>
#include <float.h> // Required for DBL_EPSILON
double sum(double x) {
   double sum = 1;
   int i = 2;
   double addVal = pow(x,(double)i)/factorial(i);

   while(addVal > DBL_EPSILON) {
      sum += addVal;
      i++;
      addVal = pow(x,(double)i)/factorial(i);
   } 

   return sum;
}
BTW, nice thinking about the EPSILON thing.
 

saint19

Distinguished
Mar 20, 2009
270
0
19,060
I think that this can help you

# include <iostream>
# include <cmath>

int main ()
{
float n,y=1,f,x,s=0;

std::cout<<"Enter the number \n";
std::cin>>n;

for (x=1; x<=n; x++)
{
y=(x*y);
f=y;
s=s+f;

}

std::cout<<f;
return 0;
}

 

mindless728

Distinguished
Jul 15, 2008
130
0
18,660
@Zenthar the nice thing about defining the constant yourself you can choose how precise it is to tweak the speed a little bit to run faster or more precise
 

Zenthar

Distinguished
Dec 31, 2007
250
0
18,960
Good point.

I also wondered if taking an optional maximum value for "n" ("i" in the code) would also be something useful. To get the rate of convergence for different values of "x" and "n" for example.