Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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));
    }
}
like image 867
Krishna Oza Avatar asked May 26 '14 09:05

Krishna Oza


People also ask

Which data type can store 100 factorial?

use double instead of long long int, as for 100!, long long int is too short to hold the result.

What is the factorial value of 100?

The answer of what is the factorial of 100 The number of digits in 100 factorial is 158.

How do you store a factorial in a string?

factorial(n) 1) Create an array 'res[]' of MAX size where MAX is number of maximum digits in output. 2) Initialize value stored in 'res[]' as 1 and initialize 'res_size' (size of 'res[]') as 1. 3) Do following for all numbers from x = 2 to n.


Video Answer


2 Answers

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.

like image 185
Mohit Jain Avatar answered Sep 18 '22 07:09

Mohit Jain


use double instead of long long int, as for 100!, long long int is too short to hold the result.

double getFactorial(double num)
{
    if (num <= 1)
        return 1;
    else
        return (num * getFactorial(num - 1));
}
like image 36
Dr. Debasish Jana Avatar answered Sep 22 '22 07:09

Dr. Debasish Jana