CODING JOY

The stunning potpourri of coding and mundane life

SPY NUMBER IN JAVA LANGUAGE



AMRUHA AHMED
11th May,2023.



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

blog1

DELVE DEEPER:

In order to check whether the given number is a spy number or not, we require three functions :


ALGORITHM FOR SUM FUNCTION:


ALGORITHM FOR PRODUCT FUNCTION:

The following Java program checks whether the given number is a Spy Number or not:


PROGRAM:

                
                    import java.util.*;
                    class spynumber
                    {
                        Scanner ob=new Scanner(System.in);
                        int sum(int n)
                        {
                            int s=0;//sum 
                            while(n!=0)
                            {
                                int rem=n%10;//extracting the last digit of n
                                s=s+rem;//calculating sum
                                n=n/10;//updating n
                            }
                            return s;
                        }
                        int product(int n)
                        {
                            int p=1;//product
                            while(n!=0)
                            {
                                int rem=n%10;//extracting the last digit of n
                                p=p*rem;//calculating product
                                n=n/10;//updating n
                            }
                            return p;
                        }
                        void main()
                        {
                            int n,sum,product;//n- number
                            System.out.print("Enter a number:");
                            n=ob.nextInt();
                            product=product(n);//storing value of product() in product
                            sum=sum(n);//storing value of sum() in sum
                            if(product==sum)//checking condition for spy number
                            System.out.println(n+" is a Spy Number");
                            else
                            System.out.println(n+" is not a Spy Number");
                        }
                    }


             
         
CODE COPIED

DRY RUN:


Suppose n=123 is passed as parameter to the sum function . The values of s,rem and n will be:
blog1
If we pass n=123 as parameter to the product function, the values of n,rem and p will be:
blog1
Since value returned from sum function is 6 and the value returned from product function is also 6, hence the number 123 is a spy number.


OUTPUT:

Enter a number:123
123 is a Spy Number


OUTPUT:

Enter a number:112
112 is not a Spy Number