Spy Number in Java — Definition, Logic, Examples, and Program

Learn what a Spy Number is in Java with clear explanations and examples. This blog covers the definition, logic, step-by-step approach, and a clean Java program to check whether a number is a Spy Number. Includes practice challenges to improve your number theory skills.

Spy Number in Java

A Spy Number is a special number where the sum of its digits is equal to the product of its digits. These numbers are popular in Java programs, coding assignments, and logic-building practice.

What is a Spy Number?

A number is called a Spy Number if:

Sum of digits = Product of digits

Examples

  • 112
    Digits → 1, 1, 2
    Sum = 1 + 1 + 2 = 4
    Product = 1 × 1 × 2 = 2
    ❌ Not a Spy Number
  • 123
    Digits → 1, 2, 3
    Sum = 1 + 2 + 3 = 6
    Product = 1 × 2 × 3 = 6
    ✔️ Spy Number
  • 22
    Digits → 2, 2
    Sum = 2 + 2 = 4
    Product = 2 × 2 = 4
    ✔️ Spy Number

Java Program to Check Spy Number

Steps used in this Java program:

  1. Extract each digit
  2. Calculate digit sum
  3. Calculate digit product
  4. Compare both values
public class SpyNumber {

    public static void main(String[] args) {
        int num = 123; // Change this number to test others
        int temp = num;

        int sum = 0;
        int product = 1;

        while (temp > 0) {
            int digit = temp % 10;
            sum += digit;
            product *= digit;
            temp /= 10;
        }

        if (sum == product) {
            System.out.println(num + " is a Spy Number.");
        } else {
            System.out.println(num + " is NOT a Spy Number.");
        }
    }
}
    

Properties of Spy Numbers

  • All single-digit numbers (0–9) are Spy Numbers.
  • Spy Numbers depend entirely on digit operations.
  • Most Spy Numbers have balanced digits like 22, 123, 132.

Practice Challenges

Challenge 1:

Write a Java program to print all Spy Numbers between 1 and 500.

Challenge 2:

Check whether a given number is a Spy Number without using multiplication.

Challenge 3:

Find the count of Spy Numbers within a given range.