Find M-th number whose repeated sum of digits of a number is N in C++

C++Server Side ProgrammingProgramming

In this problem, we are given two positive numbers N and M. Our task is to find the M-th number whose repeated sum of digits of a number is N. 

Problem description: Here, we need to find the Mth number whose sum of digits till the sum becomes single digit is equal to N.

Let’s take an example to understand the problem, 

Input: N = 4 M = 6

Output: 49

Solution Approach

A simple solution of the problem, is by finding all numbers and count the number whose sum of digits is N, and return m-th number.

Another solution to the problem is using formula to find M-th number whose sum of digits is equal to N,

M-th number = (m-1)*9 + N

Program to illustrate the working of our solution,

Example

Live Demo

#include <bits/stdc++.h>
using namespace std;

int main() {

   int n = 4, m = 6;
   int mNumber = (m - 1) * 9 + n;
   cout<<m<<"-th number whose repeated sum of digits of a number is "<<n<<" is "<<mNumber;
   return 0;
}

Output

6-th number whose repeated sum of digits of a number is 4 is 49
raja
Published on 25-Jan-2021 05:08:56
Advertisements