Find smallest number with given number of digits and sum of digits under given constraints | Function to find the number having sum of digits as s and d number of digits such that the difference between the maximum and the minimum digit the minimum possible ; To store the final number ; To store the value that is evenly distributed among all the digits ; To store the remaining sum that still remains to be distributed among d digits ; rem stores the value that still remains to be distributed To keep the difference of digits minimum last rem digits are incremented by 1 ; In the last rem digits one is added to the value obtained by equal distribution ; num = num + toString ( val ) ;
function findNumber ( s , d ) { var num = [ ] ; var val = parseInt ( s / d ) ; var rem = s % d ; for ( var i = 1 ; i <= d - rem ; i ++ ) { num . push ( val . toString ( ) ) ; } if ( rem != 0 ) { val ++ ; for ( var i = d - rem + 1 ; i <= d ; i ++ ) { num . push ( val . toString ( ) ) ; } } return num ; } var s = 25 , d = 4 ; var n = findNumber ( s , d ) ; for ( var i = 0 ; i < n . length ; i ++ ) { document . write ( n [ i ] ) ; }