# Spy Number In Java

In this tutorial we will see what is spy number and spy number example . We will write java program to check given number is spy or not . Spy number program in java is frequently asked interview  question in coding interview .

## What Is Spy Number

A positive integer is said to be a spy number if the sum and product of its digits are equal. In other words we can say ,  a number whose sum and product of all digits are equal is called a spy number.

## Spy Number Example

Now we discuss spy number example , Let’s take a number 1124 and check given number is spy or not . the sum of its digits is 1+1+2+4=8 and the product of its digits is 1*1*2*4=8. So given number 1124 is spy number .

## Algorithm for find spy number

Let’s discuss first algorithm for find spy number.

1. Take user input and store in variable (n).
2. Declare two variables sum and mul to store sum and multiply of digits. Initialize sum with 0 and mul with 1.
3. Find the last digit (n%10) of the given number by using the modulo operator.
4. Add the last digit to the variable sum.
5. Multiply the last digit with the mul variable.
6. Divide the given number (n) by 10. It removes the last digit.
7. Repeat from steps 3 to 6 until the number (n) becomes 0.
8. If the variable sum and mul have the same value, then the given number (n) is a spy number, else not a spy number.

## Spy Number Program In Java

Now we will write java program to check given number is spy number or not .Let’s implement given algorithm to find spy number in java

``````package com.demo.program;

import java.util.Scanner;

public class SpyNumber {

public static void main(String[] args)
{

int r, n, num, mul = 1, sum = 0;
Scanner sc = new Scanner(System.in);
System.out.print("Enter a number=");
n = sc.nextInt();
num = n;
while (num > 0)
{
r = num % 10;
sum = sum + r;
mul = mul * r;
num = num / 10;
}
if (mul == sum)
{
System.out.println("Given number "+ n +" is spy number");
}
else
{
System.out.println("Given number "+ n+" is not spy number");
}
}

}``````

Output :

``````Enter number=1124
Given number 1124 is  spy number``````

We  learned what is spy number , spy number example and how to check given number is spy or not in java . We also written spy number program in java in this tutorial . you can see more java program for interview preparation