Find smallest number with given number of digits and sum of digits under given constraints | C ++ implementation of the approach ; 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 ; Driver function
#include <bits/stdc++.h> NEW_LINE using namespace std ; string findNumber ( int s , int d ) { string num = " " ; int val = s / d ; int rem = s % d ; int i ; for ( i = 1 ; i <= d - rem ; i ++ ) { num = num + to_string ( val ) ; } if ( rem ) { val ++ ; for ( i = d - rem + 1 ; i <= d ; i ++ ) { num = num + to_string ( val ) ; } } return num ; } int main ( ) { int s = 25 , d = 4 ; cout << findNumber ( s , d ) ; return 0 ; }