Java Program to Check Spy Number

Mathematics for Programming Numbers (Article) Numbers (Program)

75

Given Input:

 int[] testNumbers = {112, 123, 22, 132};

Expected Output:

Checking Spy Numbers:
112 is NOT a Spy Number.
123 is a Spy Number!
22 is a Spy Number!
132 is a Spy Number!
Press any key to continue . . .

Program:

public class SpyNumberChecker {

    // Method to check if a number is a Spy Number
    public static boolean isSpyNumber(int number) {
        int sum = 0, product = 1, digit;

        // Extract digits and calculate sum and product
        while (number > 0) {
            digit = number % 10; // Get the last digit
            sum += digit;       // Add to sum
            product *= digit;   // Multiply to product
            number /= 10;       // Remove the last digit
        }

        // Check if sum equals product
        return sum == product;
    }

    public static void main(String[] args) {
        // Test numbers
        int[] testNumbers = {112, 123, 22, 132};

        System.out.println("Checking Spy Numbers:");
        for (int num : testNumbers) {
            if (isSpyNumber(num)) {
                System.out.println(num + " is a Spy Number!");
            } else {
                System.out.println(num + " is NOT a Spy Number.");
            }
        }
    }
}

Output:

Checking Spy Numbers:
112 is NOT a Spy Number.
123 is a Spy Number!
22 is a Spy Number!
132 is a Spy Number!
Press any key to continue . . .

This Particular section is dedicated to Programs only. If you want learn more about Mathematics for Programming. Then you can visit below links to get more depth on this subject.