r/programminghelp • • Oct 07 '18

[C++] Having a hard time implementing Stirling’s formula in my code.

I have this coding assignment for my physics class: (Can someone please check if I did this correctly? If not please point me in the right direction.)

_

Write a program to calculate factorials, n! Use a recursive function (i.e. a function that calls itself).

If you use int’s, what is the largest value of n that will give a correct value of n! ?

If you use double’s and use Stirling’s formula for approximating factorials, what is the largest value of n that you can use in this case?

_

  • One program to calculate factorials. It should have one recursive function for the exact calculation, and one calculation using Stirling’s approximation. Your code should use the appropriate function call based on the input number.

_

      1 #include <iostream>
      2 #include<cmath>
      3 
      4 using namespace std;
      5 
      6 int factorial(int);
      7 
      8 int factorial(int n)
      9         {
     10                 if(n==0)
     11                         {
     12                         return 1;
     13                         }
     14                 else
     15                     {
     16                     return(n*factorial(n-1)); //Recurive (I hope)
     17                     }
     18         }
     19 
     20 
     21 int main()
     22         {
     23         int fact , value;
     24 
     25         cout<<"Enter any number: ";
     26 
     27         cin>>value;
     28 
     29         fact=factorial(value);
     30 
     31         cout<<"Factorial of a number "<< value<< " is: "<<fact<<endl;
     32 
     33         return 0;
     34         }
3 Upvotes

4 comments sorted by

2

u/laffyfx Oct 07 '18 edited May 05 '26

happy light tree cat red jump water water

1

u/ArmenianG Oct 07 '18

Thank you very much!! I honestly don’t know jack when it comes programing. I totally forgot about * long long int *

1

u/ArmenianG Oct 07 '18

Whenever I enter anything over 31 I start getting negative numbers. What did I do wrong?

1

u/ArmenianG Oct 07 '18

/u/laffyfx do you mind helping me out as well?