# Count numbers from a given range that can be expressed as sum of digits raised to the power of count of digits

• Difficulty Level : Hard
• Last Updated : 15 Nov, 2021

Given an array arr[] consisting of queries of the form {L, R}, the task for each query is to count the numbers in the range [L, R] that can be expressed as the sum of its digits raised to the power of count of digits.

Examples:

Input: arr[][] = {{8, 11}}
Output: 2
Explanation:
From the given range [1, 9], the numbers that can be expressed as the sum of its digit raised to the power of count of digits are:

1. 8: Sum of digits = 8, Count of digit = 1. Therefore, 81 is equal to the given number.
2. 9: Sum of digits = 9, Count of digit = 1. Therefore, 91 is equal to the given number.

Therefore, the count of such numbers from the given range is 2.

Input: arr[][] = {{10, 100}, {1, 400}}
Output: 0 11

Naive Approach: The simplest approach is to iterate over the range arr[i][0] to arr[i][1] for each query and print the count of such numbers.

Time Complexity: O(Q*(R – L)*log10R), where R and L denote the limits of the longest range.
Auxiliary Space: O(1)

Efficient Approach: The above approach can be optimized by precomputing and storing all the numbers whether they can be expressed as the sum of its digit raised to the power of count of digits or not. Finally, print the count for each query efficiently.
Follow the steps below to solve the problem:

• Initialize an auxiliary array, say ans[], to store at ans[i], whether i can be expressed as the sum of its digit raised to the power of count of digits.
• Iterate over the range [1, 106] and update the array ans[] accordingly.
• Convert the array ans[] to a prefix sum array.
• Traverse the given array of queries arr[] and for each query {arr[i][0], arr[i][1]}, print the value of (ans[arr[i][1]] – ans[arr[i][1] – 1]) as the resultant count of numbers that can be expressed as the sum of its digit raised to the power of count of digits.

Below is the implementation of the above approach:

## C++

 // C++ program for the above approach#include using namespace std; #define R 100005int arr[R]; // Function to check if a number N can be// expressed as sum of its digits raised// to the power of the count of digitsbool canExpress(int N){    int temp = N;     // Stores the number of digits    int n = 0;     while (N != 0) {        N /= 10;        n++;    }     // Stores the resultant number    N = temp;     int sum = 0;     while (N != 0) {        sum += pow(N % 10, n);        N /= 10;    }     // Return true if both the    // numbers are same    return (sum == temp);} // Function to precompute and store// for all numbers whether they can// be expressedvoid precompute(){    // Mark all the index which    // are plus perfect number    for (int i = 1; i < R; i++) {         // If true, then update the        // value at this index        if (canExpress(i)) {            arr[i] = 1;        }    }     // Compute prefix sum of the array    for (int i = 1; i < R; i++) {        arr[i] += arr[i - 1];    }} // Function to count array elements that// can be expressed as the sum of digits// raised to the power of count of digitsvoid countNumbers(int queries[][2], int N){    // Precompute the results    precompute();     // Traverse the queries    for (int i = 0; i < N; i++) {         int L1 = queries[i][0];        int R1 = queries[i][1];         // Print the resultant count        cout << (arr[R1] - arr[L1 - 1])             << ' ';    }} // Driver Codeint main(){    int queries[][2] = {        { 1, 400 },        { 1, 9 }    };    int N = sizeof(queries)            / sizeof(queries[0]);    countNumbers(queries, N);     return 0;}

## Java

 // Java program for the above approachimport java.util.*;import java.io.*; class GFG{     static int R = 100005;static int[] arr = new int[R]; // Function to check if a number N can be// expressed as sum of its digits raised// to the power of the count of digitspublic static boolean canExpress(int N){    int temp = N;     // Stores the number of digits    int n = 0;     while (N != 0)    {        N /= 10;        n++;    }     // Stores the resultant number    N = temp;     int sum = 0;     while (N != 0)    {        sum += ((int)Math.pow(N % 10, n));        N /= 10;    }     // Return true if both the    // numbers are same      if (sum == temp)      return true;       return false;} // Function to precompute and store// for all numbers whether they can// be expressedpublic static void precompute(){     // Mark all the index which    // are plus perfect number    for(int i = 1; i < R; i++)    {                 // If true, then update the        // value at this index        if (canExpress(i))        {            arr[i] = 1;        }    }     // Compute prefix sum of the array    for(int i = 1; i < R; i++)    {        arr[i] += arr[i - 1];    }} // Function to count array elements that// can be expressed as the sum of digits// raised to the power of count of digitspublic static void countNumbers(int[][] queries, int N){         // Precompute the results    precompute();     // Traverse the queries    for(int i = 0; i < N; i++)    {        int L1 = queries[i][0];        int R1 = queries[i][1];         // Print the resultant count       System.out.print((arr[R1] - arr[L1 - 1]) + " ");    }} // Driver Code public static void main(String args[]){    int[][] queries = { { 1, 400 }, { 1, 9 } };    int N = queries.length;     // Function call    countNumbers(queries, N);}} // This code is contributed by zack_aayush

## Python3

 # Python 3 program for the above approachR = 100005arr = [0 for i in range(R)] # Function to check if a number N can be# expressed as sum of its digits raised# to the power of the count of digitsdef canExpress(N):    temp = N     # Stores the number of digits    n = 0    while (N != 0):        N //= 10        n += 1     # Stores the resultant number    N = temp    sum = 0    while (N != 0):        sum += pow(N % 10, n)        N //= 10     # Return true if both the    # numbers are same    return (sum == temp) # Function to precompute and store# for all numbers whether they can# be expresseddef precompute():       # Mark all the index which    # are plus perfect number    for i in range(1, R, 1):               # If true, then update the        # value at this index        if(canExpress(i)):            arr[i] = 1     # Compute prefix sum of the array    for i in range(1,R,1):        arr[i] += arr[i - 1] # Function to count array elements that# can be expressed as the sum of digits# raised to the power of count of digitsdef countNumbers(queries, N):       # Precompute the results    precompute()     # Traverse the queries    for i in range(N):        L1 = queries[i][0]        R1 = queries[i][1]         # Print the resultant count        print((arr[R1] - arr[L1 - 1]),end = " ") # Driver Codeif __name__ == '__main__':    queries = [[1, 400],[1, 9]]    N = len(queries)    countNumbers(queries, N)     # This code is contributed by SURENDRA_GANGWAR.

## C#

 // C# program for the above approachusing System; class GFG{     static int R = 100005;static int[] arr = new int[R]; // Function to check if a number N can be// expressed as sum of its digits raised// to the power of the count of digitspublic static bool canExpress(int N){    int temp = N;     // Stores the number of digits    int n = 0;     while (N != 0)    {        N /= 10;        n++;    }     // Stores the resultant number    N = temp;     int sum = 0;     while (N != 0)    {        sum += ((int)Math.Pow(N % 10, n));        N /= 10;    }     // Return true if both the    // numbers are same      if (sum == temp)      return true;       return false;} // Function to precompute and store// for all numbers whether they can// be expressedpublic static void precompute(){     // Mark all the index which    // are plus perfect number    for(int i = 1; i < R; i++)    {                 // If true, then update the        // value at this index        if (canExpress(i))        {            arr[i] = 1;        }    }     // Compute prefix sum of the array    for(int i = 1; i < R; i++)    {        arr[i] += arr[i - 1];    }} // Function to count array elements that// can be expressed as the sum of digits// raised to the power of count of digitspublic static void countNumbers(int[,] queries, int N){         // Precompute the results    precompute();     // Traverse the queries    for(int i = 0; i < N; i++)    {        int L1 = queries[i, 0];        int R1 = queries[i, 1];         // Print the resultant count        Console.Write((arr[R1] - arr[L1 - 1]) + " ");    }} // Driver Codestatic public void Main(){    int[,] queries = { { 1, 400 }, { 1, 9 } };    int N = queries.GetLength(0);     // Function call    countNumbers(queries, N);}} // This code is contributed by Dharanendra L V.

## Javascript


Output:
12 9

Time Complexity: O(Q + 106
Auxiliary Space: O(106

My Personal Notes arrow_drop_up