Friday, May 15, 2026
HomeLanguagesJavaJava Program to Check If a Number is Spy number or not

Java Program to Check If a Number is Spy number or not

A number is said to be a Spy number if the sum of all the digits is equal to the product of all digits. For performing the task we need to reverse through the number which will take log(N) time.

  Example:

Input : 22
Output:  Given number is a SPY number.
Explanation: Sum of the number is 4 (2 + 2)
             Product of the number is as 4 (2 * 2) 
Input : 1241
Output:  Given number is not a SPY number.

Approach:

  1. Calculate the sum of digits of the input Number.
  2. Calculate the product of digits of the input Number.
  3. If the sum of digits equals the product of digits then the number is Spy number otherwise not.

Below is the implementation of the above approach:

Java




// Java Program to Check If a Number is Spy number or not
import java.io.*;
  
class GFG {
    public static void main(String[] args)
    {
        int product = 1, sum = 0, ld;
        int n = 22;
  
        // calculate sum and product of the number here.
        while (n > 0) {
            ld = n % 10;
            sum = sum + ld;
            product = product * ld;
            n = n / 10;
        }
  
        // compare the sum and product.
        if (sum == product)
            System.out.println(
                "Given number is spy number");
        else
            System.out.println(
                "Given number is not spy number");
    }
}


Output

Given number is spy number

Complexity: O(log(n))

Dominic
Dominichttp://wardslaus.com
infosec,malicious & dos attacks generator, boot rom exploit philanthropist , wild hacker , game developer,
RELATED ARTICLES

2 COMMENTS

Most Popular

Dominic
32514 POSTS0 COMMENTS
Milvus
131 POSTS0 COMMENTS
Nango Kala
6892 POSTS0 COMMENTS
Nicole Veronica
12012 POSTS0 COMMENTS
Nokonwaba Nkukhwana
12107 POSTS0 COMMENTS
Shaida Kate Naidoo
7016 POSTS0 COMMENTS
Ted Musemwa
7262 POSTS0 COMMENTS
Thapelo Manthata
6975 POSTS0 COMMENTS
Umr Jansen
6963 POSTS0 COMMENTS