In this tutorial you will learn about the Program to check Spy Number in Java and its application with practical example.
In this tutorial, we will learn to create a Java Program to check Spy Numbers in Java using Java programming.
Prerequisites
Before starting with this tutorial we assume that you are best aware of the following Java programming topics:
- Java Operators.
- Basic Input and Output function in Java.
- Class and Object in Java.
- Basic Java programming.
- If-else statements in Java.
- For loop in Java.
What is Spy Number in Java
A Number is called a Spy number if sum(1+3+2=6) and product(1*3*6=6) of its digits are equal.
Example:-> Number “22”=> sum(2+2=4) and Product (2*2=4) then “22” is a Spy Number.
Program to check Spy Number in Java
In this program , we will find given number is a Spy number or not .First of all user will be prompted to enter Number and afterword we will find the given number is a Spy Number or not. Lets have look at the code.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 |
// Java Program to Check If a Number is Spy number or not import java.io.*; import java.util.Scanner; class GFG { public static void main(String[] args) { // Taking value form user.. Scanner s= new Scanner(System.in); System.out.println("Enter any number:"); int number= s.nextInt(); int copy, multi = 1, sum = 0, temp; copy=number; // calculate sum and product of the number here. while (copy > 0) { temp = copy % 10; sum = sum + temp; multi = multi * temp; copy = copy / 10; } // compare the sum and product. if (sum == multi) System.out.println( "Given number is spy number "+ number); else System.out.println( "Given number is not spy number "+number); } } |
Output
Spy number
Not a Spy number.
In the above program, we have first declared and initialized a set variables required in the program.
- number = it will hold entered number.
- copy = it will hold entered number copy.
- multi it will hold the result of multiplication of a number.
- Sum=it will hold sum of digit.
- Temp = it will old temp value of number.
Steps to Find Spy Number
- take a value from user in (number).
- take variables sum and product to store value of digit sum and product .
- Initialize sum with 0 and product with 1.
- Find the digit (copy%10) of a given number.
- Add digit to the variable sum=sum+temp;
- Multiply the digit with the multi= multi*temp;
- Divide the number (number) by 10 to removes the last digit.
- Repeat steps until the number become 0(Zero).
- at last check values of sum and product are same, then number is a spy number,
- else not a spy number.