Friday, November 15, 2013

Sum of factorials

Given the first few factorials:
1! = 1
2! = 2 x 1 = 2
3! = 3 x 2 x 1 = 6
4! = 4 x 3 x 2 x 1 = 24
What is the sum of the first 15 factorials, NOT INCLUDING 0!?

Language C++ :

#include<iostream>
using namespace std;

class fact {
 
          private:
                 unsigned long long int num,sum;
          public:
                 fact() {
                       num = 0;
                       sum = 0;
                 }
                 void fact1() {
                       int i;
                       for(i = 1 ; i <= 15 ; i++) {
                                 sum = sum + factorial_finder(i); 
                       }
                       cout<<"Sum of first 15 factorials is = "<<sum<<endl;
                  }
                  long long int factorial_finder(int val) { 
                                 unsigned long long int i,f = 1;
                                 for (i = 1 ; i <= val ; i++) {
                                               f = f*i;
                                 }
                                 return(f);
                   }
};

int main() {
        fact obj;
        obj.fact1();
        return(0);
}

Output: 

1401602636313

Unsigned long long long int is of 8 Bytes (64 Bits) 

Environment used to run this program :
  • Gcc compiler
  • Ubuntu 11.10 (Linux)
  • vim editor
By +Dixit Singla


No comments: