Find Nth positive number whose digital root is X in C++


In this problem, we are given two integer values N and X. Our task is to create a program to Find Nth positive number whose digital root is X.

Digital Root (X) is a single digit positive number which is found by adding digits of N recursively adding digits, till the sum becomes single digit.

Let’s take an example to understand the problem,

Input

N = 5, X = 4

Output

40

Solution Approach

A simple way to solve the problem is by counting the numbers with a digital root is X. For this, we will start from 1 and then check if the current number’s digital root is equal to X and count the numbers and return Nth such number.

Program to illustrate the working of our solution,

Example

 Live Demo

#include <iostream>
using namespace std;
int calcDigitalRoot(int num) {
   int digitSum = 1000, number = num;
   while (digitSum >= 10) {
      digitSum = 0;
      while (number > 0) {
         digitSum += number % 10;
         number /= 10;
      }
      number = digitSum;
   }
   return digitSum;
}
int calcNthDigitalRoot(int X, int N) {
   int countDigitalRootVals = 0;
   for (int i = 1; countDigitalRootVals < N; ++i) {
      int digitalRoot = calcDigitalRoot(i);
      if (digitalRoot == X) {
         ++countDigitalRootVals;
      }
      if (countDigitalRootVals == N)
         return i;
   }
   return -1;
}
int main(){
   int X = 4, N = 5;
   cout<<N<<"th positive number whose digital root is "<<X<<" is "<<calcNthDigitalRoot(X, N);
   return 0;
}

Output

5th positive number whose digital root is 4 is 40

Efficient approach

An efficient approach to solve the problem is by finding the Nth number with digital root equal to X using the direct formula which is,

Nth number = (N + 1)*9 + X

Program to illustrate the working of our solution,

Example

 Live Demo

#include <iostream>
using namespace std;
int calcNthDigitalRoot(int X, int N) {
   int nthNumber = (((N - 1) * 9) + X);
   return nthNumber;
}
int main() {
   int X = 4, N = 12;
   cout<<N<<"th positive number whose digital root is "<<X<<" is "<<calcNthDigitalRoot(X, N);
   return 0;
}

Output

12th positive number whose digital root is 4 is 103

Updated on: 13-Mar-2021

90 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements