Find the Largest number with given number of digits and sum of digits | C ++ program to find the largest number that can be formed from given sum of digits and number of digits . ; Prints the smalles possible number with digit sum ' s ' and ' m ' number of digits . ; If sum of digits is 0 , then a number is possible only if number of digits is 1. ; Sum greater than the maximum possible sum . ; Create an array to store digits of result ; Fill from most significant digit to least significant digit . ; Fill 9 first to make the number largest ; If remaining sum becomes less than 9 , then fill the remaining sum ; Driver code
#include <iostream> NEW_LINE using namespace std ; void findLargest ( int m , int s ) { if ( s == 0 ) { ( m == 1 ) ? cout << " Largest ▁ number ▁ is ▁ " << 0 : cout << " Not ▁ possible " ; return ; } if ( s > 9 * m ) { cout << " Not ▁ possible " ; return ; } int res [ m ] ; for ( int i = 0 ; i < m ; i ++ ) { if ( s >= 9 ) { res [ i ] = 9 ; s -= 9 ; } else { res [ i ] = s ; s = 0 ; } } cout << " Largest ▁ number ▁ is ▁ " ; for ( int i = 0 ; i < m ; i ++ ) cout << res [ i ] ; } int main ( ) { int s = 9 , m = 2 ; findLargest ( m , s ) ; return 0 ; }