Program to find Largest Number with Given Digits and Sum

Given the number of digits “N” and sum “S” of all the digits. Write a program to find the largest number of N digits that can be possible with given sum S.
For eg:
Input – Digit – 5, Sum – 12
Output – 93000
Input – Digit – 4, Sum – 23
Output – 9950

Algorithm

  • Iterate through a loop defined by provided digit values.
    • If sum > 9
      • Number = Number * 10 + sum
      • Sum -= 9
    • Else
      • Number = Number * 10 + sum
      • Sum -= sum
  • Number will contain the largest number of N digits that can be possible with given sum S.

Implementation

Let’s have a look into the sample program to solve above problem.

/*
 * Given the number of digits N as well as the sum S of all the digits,
 * Find the largest number of N digits that can be possible with given sum S.
 * Input:    Digits = 5   Sum = 12 
 * Output:  93000 
 * 
 */
#include <iostream>

using namespace std;

int main ()
{
	int digit = 0;
	int sum = 0;

	cout << "Enter Digits" << endl;
	cin >> digit;

	cout << "Enter Sum" << endl;
	cin >> sum;
	
	int sum_provided = sum;

	int number = 0;

	for (int i = 0; i < digit; i++)
	{
		if (sum > 9) {
			number = number * 10 + 9;
			sum -= 9;
		} else {
			number = number * 10 + sum;
			sum -= sum;
		}
	}
	cout << "Highest number with Digits: " << digit << " and sum: " << sum_provided << " is: " << number << endl;
}

Let’s look into the output of the above program.

-------------- Scenario 1 ------------------------------
Enter Digits
5
Enter Sum
12
Highest number with Digits: 5 and sum: 12 is: 93000

-------------- Scenario 2 ------------------------------
Enter Digits
4
Enter Sum
23
Highest number with Digits: 4 and sum: 23 is: 9950

Leave a Reply

Your email address will not be published. Required fields are marked *