Smallest Integer Program ISC 2015 Practical

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

import java.io.*;
class Smallest{
    public static void main(String args[])throws IOException{
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        System.out.print("M = ");
        int m = Math.abs(Integer.parseInt(br.readLine()));
        System.out.print("N = ");
        int n = Math.abs(Integer.parseInt(br.readLine()));
        if(n < 100 && m >= 100 && m <= 10000){
            int sum = 0;
            int value = m;
            do{
                value++;
                sum = sumOfDigits(value);
            }while(sum != n);
            System.out.println("The required number = " + value);
            int count = countDigits(value);
            System.out.println("Total number of digits = " + count);
        }
        else
            System.out.println("INVALID INPUT");
    }
    public static int sumOfDigits(int n){
        int sum = 0;
        for(int i = n; i != 0; i /= 10)
            sum += i % 10;
        return sum;
    }
    public static int countDigits(int n){
        int c = 0;
        for(int i = n; i != 0; i /= 10)
            c++;
        return c;
    }
}

Algorithm

1. START
2. INPUT M
3. INPUT N
4. IF N < 100 AND M >= 100 AND M <= 10000:
       SUM = 0
       VALUE = M
       REPEAT WHILE SUM != N:
           VALUE = VALUE + 1
           SUM = SUMOFDIGITS(VALUE)
       PRINT "THE REQUIRED NUMBER = " + VALUE
       COUNT = COUNTDIGITS(VALUE)
       PRINT "TOTAL NUMBER OF DIGITS = " + COUNT
5. ELSE:
       PRINT "INVALID INPUT"

2 thoughts on “Smallest Integer Program ISC 2015 Practical

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.