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));
}
}
use double instead of long long int, as for 100!, long long int is too short to hold the result.
The answer of what is the factorial of 100 The number of digits in 100 factorial is 158.
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.
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.
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));
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With