📜  查找第M个数字,该数字的重复位数为N

📅  最后修改于: 2021-04-29 02:08:44             🧑  作者: Mango

给定两个正整数N和M。任务是找到第M个数字,该数字的数字总和直到N变为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.

天真的方法是对所有数字进行迭代,并保留一个总和为N的数字的计数。

一种有效的方法是找到数字的总和,直到它变成O(1)的单个数字为止,此处已进行了讨论。因此,找到第M个数的公式将是:

下面是上述方法的实现:

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 N
int findNumber(int n, int m)
{
    int num = (m - 1) * 9 + n;
    return num;
}
  
// Driver Code
int 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 N
class GFG
{
  
// 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;
    return num;
}
  
// Driver Code
public 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 N
def findNumber(n, m) :
      
    num = (m - 1) * 9 + n; 
    return num; 
  
# Driver Code 
if __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 N
using System;
  
class GFG
{
  
// 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;
    return num;
}
  
// Driver Code
public static void Main()
{
    int n = 2, m = 5;
    Console.Write(findNumber(n, m));
}
}
  
// This code is contributed
// by Akanksha Rai


PHP


输出:
38