What to write for this C++ program?

Status
Not open for further replies.
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
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.
 
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;
}

 

Zenthar

Distinguished
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.
 
Status
Not open for further replies.