Spy Number In Java Best 2024 | topperbhai.com

 Spy Number in Java Trick 2024

Spy Number In Java 2022 Trick

 What Is  a 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 the digits. 

For  example:- If the input number is 1124, the sum of it's digits (1+1+2+4=8) is the same as  product of all the digits (1*1*2*4=8)

 Spy numbers between 1 and 1000 are: 1 2 3 4 5 6 7 8 9 22 123 132 213 231 312 321

 

In this tutorial, first we will learn how to write the Spy Number in Java Algorithm, after that we will write the code of  Spy Number in Java program to check whether the input number is Spy or not.


Spy Number in Java Algorithm:-

Step 1:  Initialize a number (n).

Step 2:  Extract the last digit (extract) of the number.

Step 3:   Find the sum of digits  of the number (sumofdigs).

Step 4:  Find the products of digits of the number (productofdigs).

Step 5:  Repeat steps 2 to 5 until the input number becomes 0.

Step 6:  If the sum of digits (sumofdigs) are equal to the product of digits (productsofdigs), then the number is a Spy number otherwise not.


For  example:- 

= 1124

 = 1+1+2+4=8

 = 1*1*2*4=8


The number 1124 is a spy number because  the sum of all digits and product of all digits of represent the same result i.e. 8.


In this post, I will write a simple java program to check whether the number input by the user is a spy number or not.


Basically, the logic I have implemented in this program is pretty simple.


I will ask the user to enter a number then, pick each digit (Starting from the last digit) of the given number and find the sum  and product  of the digit.


Repeat this process till the first digit then, add all digits and multiply all digits. Finally, I will check if the sum and product of  all  digits are equal to number or not. 


 

Spy Number In Java using While Loop

 import java.util.*;  
 class Spy_Number  
 {  
   public static void main()  
   {  
     Scanner sc=new Scanner(System.in);  
     int n,sumofdigs=0,productofdigs=1,extract;  
     System.out.println("Enter any number");  
     n=sc.nextInt(); //Example: n=1124  
     while(n!=0)  
     {  
       extract=n%10; //Extract digits(Ex.1124%10=4)  
       sumofdigs=sumofdigs+extract; //Find sum of digits(Ex.sumofdigs=0+4; )  
       productofdigs=productofdigs*extract; //Find product of digits  
       n=n/10; //Reduces number(Ex. 1124/10=112)  
     }  
     if(sumofdigs==productofdigs)  
     {  
       System.out.println("It is a spy Number");  
     }  
     else  
     {  
       System.out.println("It is not a spy Number");  
     }  
   }  
 }  
 -----------------  
 OUTPUT:-  
 ----------------  
 Enter any Number  
 1124  
 It is a Spy Number  

Post a Comment

0 Comments