Count Digits in A Factorial Geeks For Geeks

 Problem Link:


https://practice.geeksforgeeks.org/problems/count-digits-in-a-factorial3957/1#



Solution:


class Solution{

    static int facDigits(int n){

        double a=0.0;

        for(int i=2;i<=n;i++){

            a=a+Math.log10(i);

        }

       a=a+1;

        return (int)a;

    }

}


TIME:O(N)[Here we are traversing the whole array once starting from 2 and taking the sum of all log values of numbers.][GFG Time:0.1/1.2]

SPACE:O(1)[No array or any memory consuming data structure is used]

AUXILLARY SPACE:O(1)[No extra space required]

Total Test Cases:290


APPROACH:

1.We know that log(a*b)=log(a)+log(b)

and for factorial, we can write,

factorial of number n = 1*2*3*4*.......................*n

and log(1*2*3*4*.......................*n)=log(1)+log(2)+log(3)+log(4)+......................................+log(n)

Using this approach instead of multiplying every number we will directly calculate the sum of log values of every number coming between 2 to n.

if we see log values are in decimal so we have used the double variable to store the values. After loop iterations, we will add 1 in variable and later we will convert it into int and return.

Addition of 1 is by observation. If you take example of 1 then its factorial is 1 and then log(1) will be zero but digit count should be 1. So after final calculation we add 1 and return int. 

Returing int after typecasting double value is same to returing floor value of int.

So here we count the value and return the total number of digits present in the factorial.



"Thanks for Reading.😇"

"Share Further To Increase Knowledge Treasure.😊"


Comments

Popular posts from this blog

Solutions Of Practice Questions Dated 01-06-2022

CODEFORCES SPY DETECTED ROUND 713

Maximum Winning Score Geeks For Geeks