I tried my hand at a grade XII Board exam program:
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, the minimum number is 119 whose digits add up to N. 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.
I solved the program, but as a curious person, I would love to know how to increase it's efficiency, compiler time delays, and if the program could be even shorter in length. So the primary question is, what modifications need be made in my code so that it becomes more compiler-friendly and efficient?
import java.util.Scanner;
public class ISC {
static Scanner sc =new Scanner(System.in);
static int m,n; static int ndigit;
void input(){
System.out.println("Enter the value of M: ");
m = sc.nextInt();
if (m>=100&&m<=10000) {
}
else {
System.out.println("INVALID, Enter again: ");
while (!(m>=100&&m<=10000)){
m = sc.nextInt();
}
}
System.out.println("Enter the value of N: ");
n = sc.nextInt();
if (n>=1&&n<=100){
//do nothing
}
else {
System.out.println("INVALID INPUT, Enter again");
while (!(n>=1&&n<=100)){
n = sc.nextInt();
}
}
}
static int sumOfDigits(int n){
int sum = 0;
String a = Integer.toString(n); int digit;
for (int i = 0; i<a.length();i++){
digit = Integer.parseInt(Character.toString(a.charAt(i)));
sum += digit;
}
return sum;
}
static int getNo(){
ndigit = 0;
for (int i = m; i<=10000;i++){
if (sumOfDigits(i)==n){
ndigit = (Integer.toString(i)).length();
return i;
}
}
return 0;
}
public static void main(String[] args){
ISC a = new ISC();
a.input();
if (getNo()==0) System.out.println("NO NUMBER FOUND");
else {
System.out.println("Minimum number is: " + getNo());
System.out.println("Total number of digits: " + ndigit);
}
}
}