Count digits in a factorial | Set 2 | An optimised java program to find the number of digits in a factorial ; Function returns the number of digits present in n ! since the result can be large , long long is used as return type ; factorial of - ve number doesn 't exists ; base case ; Use Kamenetsky formula to calculate the number of digits ; Driver Code
import java . io . * ; import java . util . * ; class GFG { public static double M_E = 2.71828182845904523536 ; public static double M_PI = 3.141592654 ; static long findDigits ( int n ) { if ( n < 0 ) return 0 ; if ( n <= 1 ) return 1 ; double x = ( n * Math . log10 ( n / M_E ) + Math . log10 ( 2 * M_PI * n ) / 2.0 ) ; return ( long ) Math . floor ( x ) + 1 ; } public static void main ( String [ ] args ) { System . out . println ( findDigits ( 1 ) ) ; System . out . println ( findDigits ( 50000000 ) ) ; System . out . println ( findDigits ( 1000000000 ) ) ; System . out . println ( findDigits ( 120 ) ) ; } }