Count digits in a factorial | Set 2 | A optimised program to find the number of digits in a factorial ; 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
#include <bits/stdc++.h> NEW_LINE using namespace std ; long long findDigits ( int n ) { if ( n < 0 ) return 0 ; if ( n <= 1 ) return 1 ; double x = ( ( n * log10 ( n / M_E ) + log10 ( 2 * M_PI * n ) / 2.0 ) ) ; return floor ( x ) + 1 ; } int main ( ) { cout << findDigits ( 1 ) << endl ; cout << findDigits ( 50000000 ) << endl ; cout << findDigits ( 1000000000 ) << endl ; cout << findDigits ( 120 ) << endl ; return 0 ; }