Subscribe Us

Spy Number In Java

Spy Number In Java


Java Program To Check Spy Number or Not

Spy Number A number is said to be a Spy number if the
sum of all the digits is equal to the product of all digits.


Example :
Given Number : 1412
Sum of all the Digits = 1+4+1+2 = 8
Product of all the Digit = 1*4*1*2 = 8
1412 is a Spy Number
Since ,
Sum of all the digits is equal to the product of all digits.

To check if a number is a Spy Number in Java
you can use the following algorithm:
  1. Read the input number.
  2. Initialize variables sum and product to 0 and 1 respectively.
  3. While the number is not equal to 0, perform the following steps:
    • Get the last digit of the number by using the modulo operator (%).
    • Add the last digit to the sum.
    • Multiply the last digit to the product.
    • Divide the number by 10 to remove the last digit.
  4. Check if the sum is equal to the product.
    • If they are equal, the number is a Spy Number.
      Otherwise, it is not.
  5. Print the result.

In this algorithm, the input number is processed by extracting each digit and adding it to the sum variable and multiplying it to the product variable. Then, the algorithm checks if the sum is equal to the product. If they are equal, the number is considered a Spy Number.

Please note that this implementation assumes that the input number is a positive integer. You may need to add additional checks for negative numbers or other cases depending on your requirements.

Here is an example implementation in Java

Source Code

//Java Program To Check Spy Number or Not
import java.util.*;
public class SpyNumber
 {
  public static void main(String args[])
   {
     Scanner in=new Scanner(System.in);
     int num ,Rd,sum=0,pro=1;
     System.out.print("Enter a Number To Check : ");
     num=in.nextInt();
     while(num!=0)
      {
        Rd = num % 10 ;
        sum= sum + Rd ;
        pro= pro * Rd ;
        num= num / 10 ;
      }
     if(sum==pro)
      System.out.print("It is a Spy Number . ");
     else
      System.out.print("It is Not a Spy Number . ");
   }
 }

Output

Sample Input :
Enter a Number To Check : 123
Sample Output:
It is a Spy Number

Sample Input :
Enter a Number To Check : 1421
Sample Output:
It is a Spy Number

Sample Input :
Enter a Number To Check : 125
Sample Output:
It is Nota Spy Number

Looping Related Programs