# Find M-th number whose repeated sum of digits of a number is N

• Last Updated : 16 Jun, 2022

Given two positive integers N and M, The task is to find the M-th number whose sum of digits of a number until the sum becomes a single digit is N.
Examples:

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 numbers whose sum returns N.
An efficient approach is to find the summation of digits till it becomes single digits in O(1) which has been discussed here. Hence the formula to find the M-th number will be:

Mth number: (M-1)*9 + N

Below is the implementation of the above approach:

## C++

 // C++ program to Find m-th number whose// sum of digits of a number until// sum becomes single digit is N#include using namespace std; // Function to find the M-th// number whosesum till one digit is Nint findNumber(int n, int m){    int num = (m - 1) * 9 + n;    return num;} // Driver Codeint main(){     int n = 2, m = 5;    cout << findNumber(n, m);    return 0;}

## Java

 // Java program to Find m-th number whose// sum of digits of a number until// sum becomes single digit is Nclass GFG{ // Function to find the M-th// number whosesum till one digit is Nstatic int findNumber(int n, int m){    int num = (m - 1) * 9 + n;    return num;} // Driver Codepublic static void main(String args[]){    int n = 2, m = 5;    System.out.print(findNumber(n, m));}} // This code is contributed// by Akanksha Rai

## Python3

 # Python3 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 Ndef findNumber(n, m) :         num = (m - 1) * 9 + n;    return num; # Driver Codeif __name__ == "__main__" :     n = 2 ;    m = 5 ;    print(findNumber(n, m))     # This code is contributed by Ryuga

## C#

 // C# program to Find m-th number whose// sum of digits of a number until// sum becomes single digit is Nusing System; class GFG{ // Function to find the M-th// number whosesum till one digit is Nstatic int findNumber(int n, int m){    int num = (m - 1) * 9 + n;    return num;} // Driver Codepublic static void Main(){    int n = 2, m = 5;    Console.Write(findNumber(n, m));}} // This code is contributed// by Akanksha Rai



## Javascript



Output:

38

Time Complexity: O(1), as we are doing constant time operations without using any loops or recursion.

Auxiliary Space: O(1), as we are not using any extra space.

My Personal Notes arrow_drop_up