Minimum number of Factorials whose sum is equal to N | Array to calculate all factorials less than or equal to N Since there can be only 14 factorials till 10 ^ 10 Hence the maximum size of fact [ ] is 14 ; Store the actual size of fact [ ] ; Function to precompute factorials till N ; Precomputing factorials ; Function to find the minimum number of factorials whose sum represents N ; Precompute factorials ; Initialize result ; Traverse through all factorials ; Find factorials ; Print min count ; Print result ; Driver program
var fact = Array ( 14 ) . fill ( 0 ) ; var size = 1 ; function preCompute ( N ) { fact [ 0 ] = 1 ; for ( var i = 1 ; fact [ i - 1 ] <= N ; i ++ ) { fact [ i ] = ( fact [ i - 1 ] * i ) ; size ++ ; } } function findMin ( N ) { preCompute ( N ) ; var originalN = N ; ans = [ ] ; for ( var i = size - 1 ; i >= 0 ; i -- ) { while ( N >= fact [ i ] ) { N -= fact [ i ] ; ans . push ( fact [ i ] ) ; } } document . write ( ans . length + " " ) ; for ( var i = 0 ; i < ans . length ; i ++ ) document . write ( ans [ i ] + " " ) ; } var n = 27 ; findMin ( n ) ;