C++: Computing Factorials

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • catgreg
    New Member
    • Sep 2008
    • 1

    C++: Computing Factorials

    I am currently working on a c++ program that computes factorials and I can't get it to work for some reason, i could really use a hint, this is what I have thus far for code:

    [code=cpp]
    #include<iostre am>
    using namespace std;
    int n;
    int i;
    int main()
    {



    cout << "Enter a positive number:";
    cin >> n;
    i=n;
    while (n > 1 )
    {
    i=i*(n-1);
    n--;



    }
    cout << i;
    return 0;
    }
    [/code]
    the code works until I hit 20, and then it sends me to a negative number. Any ideas how? thanks!
  • Ganon11
    Recognized Expert Specialist
    • Oct 2006
    • 3651

    #2
    What is 20!'s value?

    What is the maximum value an int can hold?

    Your program is working fine if you consider the maximum value an int can hold is ~2,000,000,000.

    Comment

    • archonmagnus
      New Member
      • Jun 2007
      • 113

      #3
      Ganon's right. You can do one of two things to increase your maximum (but remember that the maximum is finite), try using an "unsigned int" or try using a double-precision variable and see your results. Remember that factorials get really big, really quickly.

      I'm kind-of a numerical methods junkie and, unfortunately, you can only stick so much into a four-byte word/int. ;)

      Comment

      • Man4ish
        New Member
        • Mar 2008
        • 151

        #4
        Use log and antilog methods for calculaitng the factorial of 20 or big numbers.

        20!=20.19.18.17 ............... ..2.1
        sum= log20+log19+... ..............+ log2+log1
        factorial = antilog(sum)

        In this way you can calculate the factorial of any number.


        Regards
        Manish

        Comment

        • curiously enough
          New Member
          • Aug 2008
          • 79

          #5
          Originally posted by Man4ish
          Use log and antilog methods for calculaitng the factorial of 20 or big numbers.

          20!=20.19.18.17 ............... ..2.1
          sum= log20+log19+... ..............+ log2+log1
          factorial = antilog(sum)

          In this way you can calculate the factorial of any number.


          Regards
          Manish
          He's not asking for another method, he aready has one, a shorter one.
          PS: Your method is equivalent to scratching your right ear with your left hand.

          Comment

          • archonmagnus
            New Member
            • Jun 2007
            • 113

            #6
            In regards to Man4ish's comment: you could also read up on Stirling's Approximation for the computation of n! for n >> 1.

            Comment

            Working...