Python: Spy number or not?

Featured Img Spy Number

In this article, we will explore the concept of spy numbers and learn how to check if a number is a spy number using Python. We’ll dive straight into examples and provide a step-by-step guide to check for a spy number in Python.

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.

Steps to 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” with “Step 1: Take the input of the number.
  • Step 2: Create two variables, one to store the sum and the other for the product.
  • Step 3: Iterate over the number’s digits 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 are equal, it’s a Spy Number; otherwise, it’s not a Spy Number

Python Code to Identify Spy Numbers

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))

Sample Outputs of the Code

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

Through this tutorial, you have gained an understanding of the concept of spy numbers and how to identify them using Python. We discussed the steps required to create an algorithm that determines whether a given number is a spy number or not. The Python code provided serves as a reliable and accurate tool for identifying spy numbers, as demonstrated by the sample outputs.

Now that you have learned about spy numbers, why not challenge yourself and explore other fascinating number patterns using Python? What other unique number properties can you uncover, and how might they be applied in real-world situations or problem-solving? Happy coding and discovering!