This program takes two numbers M(<10k) and N (<100) and finds the smallest number greater than M whose sum of digits = N. Additionally, as per the question's requirements, it prints the number of digits in the printed number.
Example: M = 919 , N = 34
Required number = 7999 as 7+9+9+9 = 34
/**
*Takes M and N , finds the number greater than M whose sum of digits = N
*/
import java.util.*;
class MtoN
{
static int sumOfdigits(int n)
{
int sum =0 ;
while(n!=0)
{
sum = sum + n%10;
n = n/10;
}
return sum;
}
static int numOfdigits(int n)
{
String str = Integer.toString(n);
return str.length();
}
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
System.out.println("Enter M (100 to 10000)");
int M = sc.nextInt();
System.out.println("Enter N (less than 100)");
int N = sc.nextInt();
if(N> 100 || M>10000 || M<100)
{
System.out.println("INVALID INPUT");
}
else
{
for(int i = M+1 ; ; i++)
{
if(sumOfdigits(i) == N)
{
System.out.println("Required Number is: "+ i);
System.out.println("Number of digits in it "+ numOfdigits(i));
break;
}
}
}
}
}
It works fine for smaller number but takes TOO much time for numbers like: M = 9181 and N = 99. (In fact, it doesn't even print the result on my screen...)
How do I reduce this execution time?
M = 9181; N = 99
, note that the sum ofLong.MAX_VALUE
's digits is only 88.Integer/MAX_VALUE
's is only 46. You're going to needBigInteger
to be able to calculate this.int
s, and evenlong
s aren't big enough to hold the required numbers. \$\endgroup\$ – Carcigenicate Jan 31 at 21:47