Given two positive integers N and M. The task is to find M-th number whose sum of digits of a number until sum becomes single digit is N.
Input: N = 1, M = 3 Output: 19 The first two numbers being 1 and 9. Input: N = 2, M = 5 Output: 38 The first four numbers being 2, 11, 20 and 29.
A naive approach is to iterate for all numbers and keep a count of number whose sum returns N.
An efficient approach is to find the summation of digits till it becomes single digits in O(1) that has been discussed here. Hence the formula to find M-th number will be:
Mth number: (M-1)*9 + N
Below is the implementation of the above approach:
Attention reader! Don’t stop learning now. Get hold of all the important mathematical concepts for competitive programming with the Essential Maths for CP Course at a student-friendly price. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.