Count of numbers whose sum of increasing powers of digits is equal to the number itself

Given an integer N, the task is to count all the integers less than or equal to N that follow the property where the sum of their digits raised to the power (starting from 1 and increased by 1 each time) is equal to the integer itself i.e. if D1D2D3…DN is an N digit number then for it to satisfy the given property (D11 + D22 + D33 + … + DNN) must be equal to D1D2D3…DN.

Examples:

Input: N = 100
Output: 11
01 = 0
11 = 1
21 = 2

91 = 9
81 + 92 = 8 + 81 = 89

Input: N = 200
Output: 13

Approach: Initialise count = 0 and for every number from 0 to N, find the sum of digits raised to the increasing power and if the resultant sum is equal to the number itself then increment the count. Finally, print the count.

Below is the implementation of the above approach:

package com.company;


public class powers {
    //Function to return the count of digits of n
    static int countDigits(int n)
    {
        int count =0;
        while (n>0)
        {
            count++;
            n=n/10;
        }
        return count;
    }
    double sum;
    //Function to return the sum of increasing powers of n
    static int digitPowsum(int n){
        int sum =0;
        /*count the digits in n which will be the power of the last digit*/
        int power = countDigits(n);
        //While there are digits left
        while(n>0){
            //Get the last digit
            int d=n%10;
            //Add the last digit after raising it to the rewuired power
            sum+=Math.pow(d,power);
            //Decrement the poer for the previous digit
            power--;
            //remove the last digit
            n/=10;


        }
     return sum;
    }
//Function which returns the count of integers which satisfy the given cndition
    static int countNum(int n){
        int count=0;
        for (int i=0;i<=n;i++)
        {
            //If current element satisfies the given condition
            if (i==digitPowsum(i))
            {
                count++;
            }

        }
        return count;
    }
    public static void main(String[] args){
        int n=100;
        System.out.println(countNum(n));
    }

}

Leave a Comment