Find Nth positive number whose digital root is X | C ++ program to find the N - th number whose digital root is X ; Function to find the digital root of a number ; Function to find the Nth number with digital root as X ; Counter variable to keep the count of valid numbers ; Find digital root ; Check if is required answer or not ; Print the answer if you have found it and breakout of the loop ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int findDigitalRoot ( int num ) { int sum = INT_MAX , tempNum = num ; while ( sum >= 10 ) { sum = 0 ; while ( tempNum > 0 ) { sum += tempNum % 10 ; tempNum /= 10 ; } tempNum = sum ; } return sum ; } void findAnswer ( int X , int N ) { int counter = 0 ; for ( int i = 1 ; counter < N ; ++ i ) { int digitalRoot = findDigitalRoot ( i ) ; if ( digitalRoot == X ) { ++ counter ; } if ( counter == N ) { cout << i ; break ; } } } int main ( ) { int X = 1 , N = 3 ; findAnswer ( X , N ) ; return 0 ; }