Java spy number program
Answers
Definition:
If the sum of digits of a number is equal to the product of its digits, then it is considered as spy number.
Sample Program:
class brainly
{
public static void main(String[] args)
{
int a,b,c,d;
b=0;
a=1;
Scanner demo = new Scanner(System.in);
System.out.println("Enter Number:");
c = demo.nextInt();
while(c != 0)
{
d = c % 10;
a = a * d;
b = b + d;
c = c / 10;
}
if(b == a)
{
System.out.println("The number is a spy");
}
else
{
System.out.println("Try Again");
}
}
}
Output:
Enter number : 132
The number is a spy.
Enter number : 148
Try again.
Hope it helps!
import java.util.*;
class spy_number
{
public void main()
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter a number to check whether it is a spy number or not");
int n=sc.nextInt();
int s=0;
int p=1;
int d=0;
int cpy=n;
while(n>0)
{
d=n%10;
s=s+d;
n=n/10;
}
while(cpy>0)
{
d=cpy%10;
p=p*d;
cpy=cpy/10;
}
if(s==p)
{
System.out.println("Spy number");
}
else
{
System.out.println("Not a spy number");
}
}
}
▶ A spy number is basically a number whose sum of digits is equal to the product of the digits .
▶ Example of a spy number is 123 where the sum of the digits is 1 + 2 + 3 = 6 and the product of the digits is the same : 1 × 2 × 3 = 6 .
▶ The spy number logic is easy and can be done by one while loop itself . However I made two while loops so that beginners in JAVA can easily understand .
▶ Perform digit extraction and then add the numbers and multiply the numbers using another variable .
▶ Then check for equality and print the required answer .