Minimum number of Factorials whose sum is equal to N | Java program to find minimum number of factorials ; 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
import java . util . * ; class GFG { static int [ ] fact = new int [ 14 ] ; static int size = 1 ; static void preCompute ( int N ) { fact [ 0 ] = 1 ; for ( int i = 1 ; fact [ i - 1 ] <= N ; i ++ ) { fact [ i ] = ( fact [ i - 1 ] * i ) ; size ++ ; } } static void findMin ( int N ) { preCompute ( N ) ; int originalN = N ; Vector < Integer > ans = new Vector < Integer > ( ) ; for ( int i = size - 1 ; i >= 0 ; i -- ) { while ( N >= fact [ i ] ) { N -= fact [ i ] ; ans . add ( fact [ i ] ) ; } } System . out . print ( ans . size ( ) + "NEW_LINE"); for ( int i = 0 ; i < ans . size ( ) ; i ++ ) System . out . print ( ans . get ( i ) + " ▁ " ) ; } public static void main ( String [ ] args ) { int n = 27 ; findMin ( n ) ; } }