C++ Program to find Numbers in a Range with Given Digital Root


The sum of its digit can find the digital root of a number; if the sum is a single digit, it is a digital root. In this tutorial, we will discuss a problem where we are given a range of numbers and an integer X, and we need to count how many numbers in the range have digital roots as X where X is a single-digit number, for example

Input: l = 13, r = 25, X = 4
Output: 2
Explanation: Numbers in the range (13,25) having digit sum 4 are 13 and 22.

Input: l = 11, r = 57
Output: 6

Approach to Find the Solution

Simple Approach

In a simple approach, we can traverse through the numbers from l to r and check whether its sum equals X. But this will create a time complexity of O(N) where N is the total number in the range.

Efficient Approach

To find numbers in a range with digital root as X, So we need to check the sum of digits of every number in the range whether it is equal to K and sum of digits always equals to num % nine and it is nine if the remainder comes 0, So if X = 9 then change it to 0.

To find the count of numbers divides the whole range into groups of 9. Then there will be exactly one number in each group whose modulo nine will be equal to X. After that, check for the left out numbers that are not in the groups; check each number separately to satisfy the condition of num % 9 = X.

Example

C++ Code for the Above Approach

#include <bits/stdc++.h>
#define ll long long int
using namespace std;
int main(){
    int l = 13;
    int r = 25;
    int X = 4;
    if (X == 9) X = 0;
    // count all the numbers in the range
    int total = r - l + 1;
    // Divide numbers into maximum groups of 9
    int groups = total/ 9;
    // since for N groups there will be N numbers with modulo 9 equals to X.
    int result = groups;
    // check all the left out numbers
    int left_out = total % 9;
    // checking each left out number separately for the condition.
    for (int i = r; i > r - left_out; i--) {
        int rem = i % 9;
        if (rem == X)
           result++;
    }
    cout << "Total Numbers in a Range( l, r ) with given Digital Root(X) are: " << result;
    return 0;
}

Output

Total Numbers in a Range( l, r ) with given Digital Root(X) are: 2

Conclusion

In this tutorial, we discussed a problem with a range of numbers and a digital root. We need to find all the numbers with digital roots as X.We discussed a simple approach and an efficient approach to solve this problem by dividing the numbers into groups of 9 digits.

Each group contains one number having a digital root as X. We also discussed the C++ program for this problem which we can do with programming languages like C, Java, Python, etc. We hope you find this tutorial helpful.

Updated on: 25-Nov-2021

146 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements