A number where the sum of all the digits is equal to the product of the digits is known as a spy number. For example,
Let us consider the number 123:
Sum of digits: 1+2+3 = 6
Product of digits: 1*2*3 = 6
Therefore, 123 is a spy number.
Other examples include: 22, 1214, 33, etc.
Let us consider the number 1441:
Sum of digits: 1+4+4+1 = 10
Product of digits: 1*4*4*1 = 16
Therefore, 1441 is not a spy number.
In this algorithm, we will see the simplest approach to check whether a given number is a spy number or not.
To check whether a given number is a spy number or not, we will have to calculate the sum of its digits as well as the product of its digits. If both the sum and product are equal, the given number will be a spy number.
We start off by taking the number to be checked, say ‘n’ from the user as input. Then, we initialize the sum of the digits of the number, ‘s’ as zero, and the product of the digits, ‘p’ as one. After this, we start a while loop, which runs until the number is not equal to zero. We then extract the last digit of the number by performing: d = n % 10. After that, the extracted digit is added to the sum of the digits, ‘s’ with the help of the statement: s = s + d. Along with the sum, we also calculate the product of the digits in the same loop. To do this, we multiply the extracted digit with ‘p’, with the help of the statement: p = p * d. This loop continues iterating until no digits are left in the number, that is when n is equal to zero.
Once this loop completes all its iterations, we check whether the calculated sum and product are equal or not, that is if ‘s’ is equal to ‘p’. If this condition is satisfied, the given number is a spy number, else, the number is not a spy number.
Note: Here ‘%’ is the modulus operator which returns the remainder value after division.