bhylu.com

Advertisements

Java Check a Digit-Power Identity

A digit-power check compares a non-negative number with the sum of each decimal digit raised to the number of digits. Define this rule before implementing a familiar named exercise.

Understand the idea

Count the decimal digits first, including the one-digit representation of zero. For this bounded int example, use long arithmetic for the sum and integer multiplication for each power. That avoids floating-point equality as the test of an integer identity. The input is small enough to keep the loop straightforward; it is not a cryptographic property or a general large-number theorem prover.

Run it locally

Use a local JDK 21 or newer. Save the complete example as Main.java in a separate lab folder, then compile and run it with the commands below. Java examples do not run in Bhylu’s browser playground. The -ea option enables assertion checks used by some lessons.

JDK and terminal setup

javac --release 21 -encoding UTF-8 -d out Main.java
java -ea -cp out Main

A worked example

Java 21+ · Main.java

public class Main {
    public static void main(String[] args) {
        int number = 9474;
        int digits = Integer.toString(number).length();
        long total = 0;
        int remaining = number;
        do {
            int digit = remaining % 10;
            long power = 1;
            for (int i = 0; i < digits; i++) power *= digit;
            total += power;
            remaining /= 10;
        } while (remaining != 0);
        System.out.println(total == number);
    }
}

Expected output

true

There are four digits, so each contributes its fourth power. The sum is 9474 and matches the source. The do/while also handles zero as a digit. A reusable method should reject negative values before converting them to text, because a minus sign is not a decimal digit.

Check the official Java documentation for detailed contracts and supported options.