Find next number whose sum of digits is N This program takes two numbers M(&lt;10k) and N (&lt;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&gt; 100 || M&gt;10000 || M&lt;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?
This is not a review, but an extended comment.

Thou shalt not brute force. Instead of inspecting every number larger than M (it indeed takes too much time), consider partitioning N into a sum of single digit numbers, and use these partitions to form the answer.

Notice that you don't have to inspect all the partitions. The digit composition of M gives enough leads to just construct the answer.