-2

Click Here to View CodeFunction to perform factorial of digit and count the number of digit of that factorial

When i give "Input:13" this code give the desired output but when i use a "Input: digit greater the this or 3 digit number" then it is unable to calculate. I think it because of the number of value unsigned long long can hold is exceeded. So is there any solution how can i find Digit of factorial for a large digit number.

///// user function code//////////////
unsigned long long int digitInFactorial(int N)
{
int count=0;
if(N==0) || (n==1)){
return 1;
}else{
int result=1;
for(int i=1;i<=N;i++){
result=result+1;}
while(result!=0)
{
result=result/10;
count=count+1;
}}
return count;
}
Tilak Raj
  • 1
  • 2
  • 3
    In case it's not obvious, exercises like this always have a trick to them. You can't just calculate the factorial and count the digits (because that's too slow and/or the number doesn't fit into an `unsigned long long`). You need some clever formula to determine the amount of digits without computing the factorial. – HolyBlackCat Dec 01 '20 at 18:56
  • The code in the screenshot is different from the code in the question. Why is that? – HolyBlackCat Dec 01 '20 at 18:58
  • Able to solve this by using log10:://////////////int digitsInFactorial(int N) { if(N<0) return 0; if(N<=1) return 1; double digit=0; for(int i=1;i<=N;i++) digit=digit+log10(i); return floor(digit)+1; } – Tilak Raj Dec 01 '20 at 19:09

1 Answers1

0
int digitsInFactorial(int N) {
    if (N < 0)
        return 0;
    
    if (N <= 1)
        return 1;
        
    double digit=0;
    
    for (int i = 1; i <= N; i++)
        digit = digit + log10(i);

    return floor(digit) + 1;
}
Michael
  • 2,758
  • 6
  • 28
  • 55
Tilak Raj
  • 1
  • 2
  • Please don't post only code as answer, but also provide an explanation what your code does and how it solves the problem of the question. Answers with an explanation are usually more helpful and of better quality, and are more likely to attract upvotes – Boken Dec 02 '20 at 00:34
  • Here we have to calcutate the number of digit a factorial of any particular number have. So for finding that i use log10 because it help to alter that big factorial to number of digit it can contain ( for further reference you can see this->[link](https://youtu.be/pQhMdvHp5oo). After that floor the result and you will be able to see to respective number of digit the your factorial have. May `log10` help you to solve this problem. – Tilak Raj Dec 05 '20 at 20:12