Smallest integer with digit sum M and multiple of N | C ++ implementation of the above approach ; Function to return digit sum ; Function to find out the smallest integer ; Start of the iterator ( Smallest multiple of n ) ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int digitSum ( int n ) { int ans = 0 ; while ( n ) { ans += n % 10 ; n /= 10 ; } return ans ; } int findInt ( int n , int m ) { int minDigit = floor ( m / 9 ) ; int start = pow ( 10 , minDigit ) - ( int ) pow ( 10 , minDigit ) % n ; while ( start < INT_MAX ) { if ( digitSum ( start ) == m ) return start ; else start += n ; } return -1 ; } int main ( ) { int n = 13 , m = 32 ; cout << findInt ( n , m ) ; return 0 ; }