# Swift Program to Check If a Number is Spy number or not

In this article, we will learn how to write a swift program to check if a number is a spy number or not. A spy number is a number in which the sum of the digits of the given number is equal to the product of the digits of the given number. For example −

Number = 123

Sum = 1 + 2 + 3 = 6

Product = 1 * 2 * 3 = 6

Hence 123 is a spy number because sum = product

Number = 23

Sum = 2 + 3 = 5

Product = 2 * 3 = 6

Hence 23 is not spy number because sum != product

## Algorithm

Step 1 − Create a function to check the spy number.

Step 2 − In this function, calculate the sum of the digits of the test number.

Step 3 − Calculate the product of the digits of the test number.

Step 4 − Check if the sum is equal to the product. If yes, then return true. Otherwise, return false.

Step 5 − Call the function and pass the number as a parameter in it to find the spy number.

Step 6 − Print the output.

## Example

Following Swift program to check if a number is a spy number or not.

import Foundation
import Glibc

// Function to check the given number is a spy number or not
func checkSpyNumber(number: Int)->Bool {
var prod = 1
var sum = 0
var num = number

// Calculating the sum and product of the given number
while (num > 0) {
let n = num % 10
sum = sum + n
prod = prod * n
num = num/10
}
if (sum == prod) {
return true
}
else{
return false
}
}

// Test cases
print("Is 22 is a spy number?:", checkSpyNumber(number: 22))
print("Is 123 is a spy number?:", checkSpyNumber(number: 123))
print("Is 49 is a spy number?:", checkSpyNumber(number: 49))
print("Is 1592 is a spy number?:", checkSpyNumber(number: 1592))


## Output

Is 22 is a spy number?: true
Is 123 is a spy number?: true
Is 49 is a spy number?: false
Is 1592 is a spy number?: false


Here in the above code, we have four different numbers. Now we create a function to check the given numbers are spy numbers or not. So for spy number first we find the individual digits of the given number and then calculate their sum using the + operator and product using the * operator. After that, we check if the sum is equal to the product or not using the == operator. If the sum is equal to the product, then the number is the spy number, otherwise, not.

## Conclusion

So this is how we can find whether the given number is the spy number or not.