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:
// Java program to Find m-th number whose
// sum of digits of a number until
// sum becomes single digit is N
// Function to find the M-th
// number whosesum till one digit is N
static int findNumber(int n, int m)
int num = (m – 1) * 9 + n;
// Driver Code
public static void main(String args)
int n = 2, m = 5;
// This code is contributed
// by Akanksha Rai
- Remove repeated digits in a given number
- Recursive sum of digits of a number formed by repeated appends
- Count ways to spell a number with repeated digits
- Find smallest number with given number of digits and sum of digits
- Find the Largest number with given number of digits and sum of digits
- Find count of digits in a number that divide the number
- Find maximum number that can be formed using digits of a given number
- Find the smallest number whose digits multiply to a given number n
- Find first and last digits of a number
- Given a number n, find the first k digits of n^n
- Find N digits number which is divisible by D
- Find next greater number with same set of digits
- Find a Number X whose sum with its digits is equal to N
- Find sum of digits in factorial of a number
- Find a number x such that sum of x and its digits is equal to given n.
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.