ISC Computer Practical 2015 Question 1

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
        The total number of digits = 3

Example 2

INPUT: M = 1500
       N = 25
OUTPUT: The required number = 1699
        The total number of digits = 4

Example 3

INPUT: M = 99
       N = 11

Example 4

INPUT: M = 112
       N = 130


import java.util.*;
class Q1{
    public static int getSumOfDigits( int n ){
        int sum=0;
        for( int temp=n; temp>0; temp/=10 ){
        return sum;
    public static int getNumOfDigits( int n ){
        int count=0;
        for( int temp=n; temp>0; temp/=10 ){
        return count;
    public static void main( String args[] ){
        int M, N, sum;
        Scanner sc = new Scanner( );
        System.out.print("INPUT:\tM= ");
        System.out.print("\tN= ");
        if( M<100 || M>10000 || N<0 || N>=100){
            System.out.println("OUTPUT:\tINVALID INPUT");
                sum = getSumOfDigits(M);
                if(sum==N ){
                    System.out.println("OUTPUT:\tThe required number="+(M));
                    System.out.println("OUTPUT:\tTotal number of digits="+getNumOfDigits(M));
                    System.out.println("No solution exist");

In the above program  was asked in the ISC Computer Practical 2015 please not that code of functions getNumberOfDigits() and getSumOfDigits() is nearly identical and the code could have been merged to obtain shorter code. But that would result in decreased efficiency because total number of digit is required only in those cases when the sum is equal to N and there is no point in calculating the same for failed cases.

Follow me

Vinay Singh

Computer Teacher at Saint John's Academy
I am a GNU/Linux enthusiast and a computer science teacher by profession based at Allahabad, India. My hobbies include reading (mostly computer related stuff) and photography.
Follow me

Latest posts by Vinay Singh (see all)

Leave a Reply