ISC practical papers › ISC 2015 › Question 1
Smallest number with a given sum
ISC 2015 Computer Science Practical, Question 1 · Number programs
The question
Given two positive numbers M and N, such that M is between 100 and 10000 and N is less than 100.
Find the smallest integer that is greater than M and whose digits add up to N. For example, if M = 100 and N = 11, then the smallest integer greater than 100 whose digits add up to 11 is 119.
Write a program to accept the numbers M and N from the user and print the smallest required number whose sum of all its digits is equal to N.
Also, print the total number of digits present in the required number.
The program should check for the validity of the inputs and display an appropriate message for an invalid input.
Test your program with the sample data and some random data:
Example 1
INPUT: M = 100
N = 11
OUTPUT: The required number = 119
Total number of digits = 3
Example 2
INPUT: M = 1500
N = 25
OUTPUT: The required number = 1699
Total number of digits = 4
Example 3
INPUT: M = 99
N = 11
OUTPUT: INVALID INPUT
Example 4
INPUT: M = 112
N = 130
OUTPUT: INVALID INPUT
Question: ISC 2015 Computer Science Paper 2 (Practical), Question 1, set by the Council for the Indian School Certificate Examinations (CISCE). Solution and video: Vinay Singh.
Java solution
import java.util.*;
class Number {
private int M, N;
String output;
private boolean status;
public Number(int M, int N) {
this.M = M;
this.N = N;
output = "";
status = false;
}
public void findSolution() {
int M = this.M;
int sum = 0;
do {
sum = sumOfDigits(M);
if (sum == N) {
output = "OUTPUT:\tThe required number = " + M + "\n\tTotal number of digits = " + countDigits(M);
status = true;
}
M++;
if (M == Integer.MAX_VALUE) {
status = false;
break;
}
} while (sum != N);
}
public boolean hasSolution() {
return status;
}
private int sumOfDigits(int n) {
int sum = 0;
for (int temp = n; temp > 0; temp /= 10) {
sum += temp % 10;
}
return sum;
}
private int countDigits(int n) {
int count = 0;
for (int temp = n; temp > 0; temp /= 10) {
count++;
}
return count;
}
public String toString() {
return output;
}
}
class ISC2015Q1 {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("INPUT:\tM = ");
int M = in.nextInt();
System.out.print("\tN = ");
int N = in.nextInt();
if (M < 100 || M > 10000 || N < 0 || N >= 100) {
System.out.println("OUTPUT:\tINVALID INPUT");
} else {
Number num = new Number(M, N);
num.findSolution();
if (num.hasSolution()) {
System.out.println(num);
} else {
System.out.println("OUTPUT:\tNo solution exists");
}
}
in.close();
}
}
All these solutions in one free book
Pragmatic Solutions to ISC Computer Science Practical Problems collects every program from 2004 to 2021 in a 202-page PDF.