factorial program

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Umangengineer
    New Member
    • Mar 2008
    • 4

    factorial program

    i want a program to do the task:
    1!+2!+3!+4!+5!=
  • sicarie
    Recognized Expert Specialist
    • Nov 2006
    • 4677

    #2
    There are a number of ways to go about this, have you created your algorithm for completing this yet?

    Also, are you going to just be printing out the final answer of that exact equation, or do you want to be able to change the highest number that it can go up to? Because if it is the first, you can just figure it out by hand and write a print statement. The latter will require actually creating an algorithm to figure out factorials.

    Comment

    • JosAH
      Recognized Expert MVP
      • Mar 2007
      • 11453

      #3
      For S(n) == 1! + 2! + 3! + n! you can easily find that S(n)= S(n-1)+ (n-1)!*n so
      if you keep the last term apart from the grand result you can always easily
      calculate the next term.

      kind regards,

      Jos

      Comment

      • fual
        New Member
        • Feb 2008
        • 28

        #4
        Originally posted by Umangengineer
        i want a program to do the task:
        1!+2!+3!+4!+5!=
        You can do this very efficiently with a function object:
        [CODE=cpp]
        class sum_fac {
        const long& operator( )( void ) {
        // compute the new factorial

        // Increase the partial sum
        return sum_;
        }
        private:
        long _i;
        long _fac;
        long _sum;
        };
        [/CODE] See if you can add in the details.

        Comment

        • Umangengineer
          New Member
          • Mar 2008
          • 4

          #5
          Thanx for the suggestion...
          I made it using nested loops....

          Comment

          • Umangengineer
            New Member
            • Mar 2008
            • 4

            #6
            Thanx for the suggestion...
            I havent done classes yet....
            I made it using nested loops....

            Comment

            • Ganon11
              Recognized Expert Specialist
              • Oct 2006
              • 3651

              #7
              Have you considered using an array to do this?

              e.g. User says to sum the first 6 number's factorials.

              You make an array of length 6. The first element (array[0]) is 1. (This represents 1!).

              Then, for any element N, assuming the previous element has already been set, the value needed in array[N-1] is array[N-2] * (N-1).

              To find the sum, add all the numbers in the array.

              This is a much faster method of calculating factorials then either nested loops or a recursive function, which are the two most common methods I've seen for calculating factorials.

              Comment

              Working...