Smallest integer with digit sum M and multiple of N | Function to return digit sum ; Function to find out the smallest integer ; Start of the iterator ( Smallest multiple of n ) ; Driver code
function digitSum ( n ) { var ans = 0 ; while ( n ) { ans += n % 10 ; n = parseInt ( n / 10 ) ; } return ans ; } function findInt ( n , m ) { var minDigit = Math . floor ( m / 9 ) ; var start = Math . pow ( 10 , minDigit ) - Math . pow ( 10 , minDigit ) % n ; while ( start < 1000000000 ) { if ( digitSum ( start ) == m ) return start ; else start += n ; } return - 1 ; } var n = 13 , m = 32 ; document . write ( findInt ( n , m ) ) ;