Sign in with
Sign up | Sign in

What to write for this C++ program?

Last response: in Applications
Share

  1. #include <math.h>
  2.  
  3. //using a 64bit int
  4. unsigned long long factorial(int n) {
  5. unsigned long long r = 1;
  6.  
  7. if(n <= 0)
  8. return 1;
  9.  
  10. for(int i = 1; i < n; i++)
  11. r *= i;
  12.  
  13. return r;
  14. }
  15.  
  16. double sum(double x) {
  17. const double epsilon = 1e-20
  18. double sum = 1;
  19. int i = 2;
  20. double addVal = addVal = pow(x,(double)i)/factorial(i);
  21.  
  22. while(addVal > epsilon) {
  23. sum += addVal;
  24. i++;
  25. addVal = addVal = pow(x,(double)i)/factorial(i);
  26. }
  27.  
  28. return sum;
  29. }

The factorial() function could be shortened a bit:
  1. //using a 64bit int
  2. unsigned long long factorial(int n) {
  3. unsigned long long r = 1;
  4.  
  5. while(n > 1)
  6. r *= n--;
  7.  
  8. return r;
  9. }

And for the sum() function, I would use the #defined constant instead of defining it yourself.
  1. #include <math.h>
  2. #include <float.h> // Required for DBL_EPSILON
  3. double sum(double x) {
  4. double sum = 1;
  5. int i = 2;
  6. double addVal = pow(x,(double)i)/factorial(i);
  7.  
  8. while(addVal > DBL_EPSILON) {
  9. sum += addVal;
  10. i++;
  11. addVal = pow(x,(double)i)/factorial(i);
  12. }
  13.  
  14. return sum;
  15. }

BTW, nice thinking about the EPSILON thing.
Related ressources

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 said:
@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
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.
Ask the community
!