What data type can store factorial 100

Why is the program below printing factorial as 0 for 100 as input. The same factorial can be calculated if the return type of the getFact function is equal long double, but to get the sum of the digits, I cannot use the mod (%) operator in a long double.

Note: size unsigned long longand long doublesame on my machine. Please suggest for input as 100. Which data type will give the correct result.

#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 <<" 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));
    }
}
+4
source share
3 answers

, double. ( ). log 100!.

, , . google .

() , , .

+4

double long long int, 100!, long long int , .

double getFactorial(double num)
{
    if (num <= 1)
        return 1;
    else
        return (num * getFactorial(num - 1));
}
+2

long double 25, - .

#include <iostream>
#include <iomanip>

using namespace std;

long double factorial(long double n)
{
    if (n<=1)
        return 1;
    else
    {
        return n*factorial(n-1);
    }
}

int main()
{
    long double fact;
    for(long double i=0;i<50;i++)
    {
        fact=factorial(i);
        cout<<i<<"!= "<<setprecision(0)<<fixed<<fact<<endl;;
    }
    return 0;
}
0

Source: https://habr.com/ru/post/1542019/


All Articles