Swift Program to Check if the given number is Perfect number or not


A perfect number is a positive number that is equal to the sum of its factors, excluding the number itself. For example −

Number = 6

Proper divisors = 1, 2, 3

Hence, 6 is the perfect number because the sum of its divisors is 6(1+2+3)

Number = 10

Proper divisors = 1, 2, 5

Hence, 10 is not a perfect number because the sum of its divisors is 8(1+2+5)

In this article, we will learn how to write a swift program to check if the given number is a perfect number or not.

Algorithm

Step 1 − Create a function.

Step 2 − Create a variable to store the sum of the divisors, sum = 0.

Step 3 − Run a for loop from 1 to number-1 and find all the divisors and add them.

Step 4 − Check if the sum is equal to the number itself. If yes, then this function return true. Otherwise return false.

Step 5 − Create a variable to store the input number.

Step 6 − Pass the input number into the function.

Step 7 − Print the output.

Example

Following the Swift program to check if the given number is the perfect number or not.

import Foundation
import Glibc

// Function to check if the given number is perfect number or not
func checkPerfect(number: Int) -> Bool {
   var sum = 0

   // Finding all the divisor and add them
   for x in 1..<number {
      if number % x == 0 {
         sum += x
      }
   }
   return sum == number
}

// Input 1
let N1 = 28
print("Is \(N1) is a perfect number?:", checkPerfect(number:N1))

// Input 2
let N2 = 8128
print("Is \(N2) is a perfect number?:", checkPerfect(number:N2))

// Input 3
let N3 = 21
print("Is \(N3) is a perfect number?:", checkPerfect(number:N3))

Output

Is 28 is a perfect number?: true
Is 8128 is a perfect number?: true
Is 21 is a perfect number?: false

Conclusion

Here in the above code, we create a function named checkPerfect() to check if the given number is a perfect number or not. This function takes a positive integer as an input and then runs a for loop to iterate through each number from 1 to number-1. Inside the for loop check if the ‘number’ is divisible by the current iterator ‘x’. If yes, then add ‘x’ to the ‘sum’. Otherwise, move to the next value, this process continues till number 1. After finding the sum of all the divisors of the given number, comparesum == number. If the sum of the divisors is equal to the number itself, then this function returns true which means the number is the perfect number. If the sum of the divisors is not equal to the number itself, then this function returns false which means the number is not a perfect number. So this is how we can check whether the given number is a perfect number or not.

Updated on: 16-Feb-2023

365 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements