Python: Spy number or not?

Featured Img Spy Number

Hello fellow coder! Today we are going to understand what a spy number is and how to decide whether a number is a spy number or not using the python programming language.

Also read: Harshad Number in Python – Easy Implementation

What is a Spy Number?

A particular number is known as a Spy number if the sum of its digits is exactly equal to the product of its digits. Let’s look at some examples:

Example 1: 1421
Sum of digits ==> 1+4+2+1 = 8
Product of digits ==> 1*4*2*1 = 8

Since the product and the sum of the digits are exactly the same, the number is a spy number

Example 2: 1342
Sum of digits ==> 1+3+4+2 = 10
Product of digits ==> 1*3*4*2 =24

Clearly, the product and sum are not equal and hence, the number is not a spy number.

Identify a Spy Number in Python

To know if a number is a spy number or not, one needs to follow some steps which are described below:

Step 1: Take the INPUT of the number
Step 2: Create two VARIABLES one to store the SUM and the other the PRODUCT
Step 3: ITERATE over the number digit one after another from RIGHT to LEFT
Step 4: On each iteration ADD the digit to the sum and MULTIPLY the same digit to the product
Step 5: After all the digits are encountered COMPARE the sum and product values: If they equal => Spy Number, otherwise => Not a Spy Number.

Now let’s look at the code following the steps we just mentioned above.

num=int(input("Enter your number "))
sum=0
product=1
num1 = num

while(num>0):
    d=num%10
    sum=sum+d
    product=product*d
    num=num//10

if(sum==product):
    print("{} is a Spy number!".format(num1))
else:
    print("{} is not a Spy number!".format(num1))

I hope you can follow the steps mentioned in the code mentioned above. Let’s look at some sample outputs.

Enter your number 123
123 is a Spy number!
Enter your number 234
234 is not a Spy number!

You can see that the code is very accurate and is giving the right results as well.

Conclusion

By end of this tutorial, you now have the knowledge of what spy number is and how to implement the same in the python programming language.

Thank you for reading!