Search code examples
c++type-conversionfactorial

What data type can store a factorial of 100


Why the below program prints the factorial as 0 for 100 as input. The same factorial can be calculated if the getFact function return type is long double, but to get sum of digits I cant appply mod (%) operator on long double.

Note: size of unsigned long long and long double is same on my machine. Kindly suggest for input as 100 What type of data would give correct output.

#include <iostream>
#include <stdlib.h>

unsigned long long int getFactorial(int);
unsigned long long int getSum(unsigned long long int);

int main()
{
    unsigned long long int fact = 1;
    unsigned long long int digsum  = 0;
    std::cout << "Enter a number to find fact := ";
    int num;
    std::cin >> num;
    fact = getFactorial(num);
    std::cout << num <<"'s factorial is = " << fact << std::endl;
    digsum = getSum(fact);
    std::cout << sizeof(unsigned long long int) << std::endl;
    std::cout << sizeof(long double) << std:: endl;
    std::cout << "Sum of the digits in the number" << num << "! is :=" <<  digsum << std::endl;
    return 0;
}

unsigned long long int getFactorial(int num)
{

    if(num == 1)
        return 1;
    else
        return (num * getFactorial(num - 1));
}


unsigned long long int getSum(unsigned long long int fact)
{
    if(fact == 0)
        return 0;
    else
    {
        int temp = 0;
        temp = fact % 10;
        return (temp + getSum(fact/10));
    }
}

Solution

  • If you want an approximation you can use double. (Beware integer arithmetic is different from double). You can use log calculation or multiplication to estimate 100!.

    But because you want the sum of digits, you need precise result, you would need some big integer library. You can google for big integer.

    Or you can store big number as string and perform your calculation (product) the way we learnt in school using pen and paper.