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));
}
}
source
share