Java Program to Check Spy Number
A spy number is a number where the sum of its digits is equal to the product of its digits.
For example, 1124 is a spy number because 1+1+2+4 = 8 and 1×1×2×4 = 8.
1. Understanding the Problem
Determine whether a given number is a spy number.
Number: 1124 → Spy Number: 123 → Not Spy Number: 22 → Spy
2. Using Basic Loop
Java
Check spy number using loop
import java.util.Scanner;
public class SpyNumber {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter a number: ");
int num = sc.nextInt();
int sum = 0;
int product = 1;
while (num != 0) {
int digit = num % 10;
sum += digit;
product *= digit;
num /= 10;
}
if (sum == product)
System.out.println("Spy Number");
else
System.out.println("Not a Spy Number");
}
}
3. Optimized Approach
Java
Check spy number using for loop
import java.util.Scanner;
public class SpyOptimized {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter a number: ");
int num = sc.nextInt();
int sum = 0, product = 1;
for (; num > 0; num /= 10) {
int digit = num % 10;
sum += digit;
product *= digit;
}
if (sum == product)
System.out.println("Spy Number");
else
System.out.println("Not a Spy Number");
}
}
4. Common Mistakes
1. Initializing product as 0 instead of 1.
2. Forgetting to extract digits correctly.
3. Not handling single-digit numbers properly.
4. Mixing sum and product logic.
5. Applications
1. Helps in understanding digit-based operations.
2. Useful for practicing loops and arithmetic logic.
3. Common beginner-level coding problem.
Conclusion
Spy number programs are simple and useful for learning digit manipulation.
They help strengthen understanding of loops and basic arithmetic operations.
Codecrown