Skip to main content

How to check if a number is a perfect number in Kotlin

How to check if a number is a perfect number in Kotlin.

Here's a step-by-step tutorial on how to check if a number is a perfect number in Kotlin:

Step 1: Understand what a perfect number is

  • A perfect number is a positive integer that is equal to the sum of its proper divisors (excluding the number itself).
  • For example, 6 is a perfect number because its proper divisors (excluding 6) are 1, 2, and 3, and their sum is 1 + 2 + 3 = 6.

Step 2: Create a function to check if a number is perfect

  • Start by defining a function called isPerfectNumber that takes an integer as its parameter and returns a Boolean value indicating whether the number is perfect or not.

Step 3: Find the divisors of the number

  • Inside the isPerfectNumber function, create a variable called divisors and initialize it as an empty list to store the divisors of the number.
  • Use a loop to iterate from 1 to the given number (excluding the number itself).
  • Check if the current iteration value is a divisor of the number by using the modulo operator (%).
  • If the remainder is 0, it means the current value is a divisor, so add it to the divisors list.

Step 4: Calculate the sum of the divisors

  • After finding all the divisors, calculate their sum by using the sum() function on the divisors list.

Step 5: Check if the sum equals the given number

  • Finally, compare the sum of the divisors with the given number.
  • If they are equal, return true from the isPerfectNumber function, indicating that the number is perfect.
  • Otherwise, return false, indicating that the number is not perfect.

Here's the complete code example:

fun isPerfectNumber(number: Int): Boolean {
val divisors = mutableListOf<Int>()
for (i in 1 until number) {
if (number % i == 0) {
divisors.add(i)
}
}
val sumOfDivisors = divisors.sum()
return sumOfDivisors == number
}

Now, you can use the isPerfectNumber function to check if a number is perfect. Here's an example usage:

fun main() {
val number = 6
if (isPerfectNumber(number)) {
println("$number is a perfect number")
} else {
println("$number is not a perfect number")
}
}

This will output: 6 is a perfect number.

You can try running the above code with different numbers to test if they are perfect numbers.