it's a beginner's problem. I am trying to calculate sum of the first 15 factorials. I know int isn't large enough for the sum, so I used unsigned long long but it still didn't work. why?? Thanks for helping!

#include <iostream>
#include <cmath>
#include <iomanip>
#include <cstring>

using namespace std;

int main()
{
    const int fac = 15;
    unsigned long long sum = 0;
    int start = 1;

    for (int i = 1; i <= fac; i++){
        start = start * i;
        sum += start;
    cout << fixed << setprecision(0) << i << "   " << sum <<endl;
    }
}

Recommended Answers

All 5 Replies

Probably depends on what compiler you are using. Here's the output from VC++ 2013

1   1
2   3
3   9
4   33
5   153
6   873
7   5913
8   46233
9   409113
10   4037913
11   43954713
12   522956313
13   2455009817
14   3733955097
15   5738265113
Press any key to continue . . .
commented: Thanks for helping. I got it to work. when it does the addition, long long got demoted to an int type. +0

As a follow up question, what if I want to calculate the sum of the first 500 factorials, what data type can I use to storage such a big number? Thanks

You would need some sort of arbitrary precision library. The GNU MP Bignum Library is pretty good.

unsigned long long sum doesn't work because start is still an int.

unsigned long long sum doesn't work because start is still an int.

That shouldn't be a problem.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.