Skip to main content

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

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

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

Step 1: Get the input number

  • Prompt the user to enter a number or initialize a variable with the desired number to be checked.

Step 2: Calculate the square root of the number

  • Use the sqrt function from the kotlin.math package to calculate the square root of the input number.
  • Assign the result to a variable.

Step 3: Check if the square root is an integer

  • Use the rem function to check if the square root has a remainder when divided by 1.
  • If the remainder is zero, it means the square root is an integer, indicating that the input number is a perfect square.
  • If the remainder is not zero, it means the square root is not an integer, indicating that the input number is not a perfect square.

Step 4: Print the result

  • Use a conditional statement (such as an if-else statement) to display the result to the user.
  • If the square root is an integer, print a message confirming that the number is a perfect square.
  • If the square root is not an integer, print a message stating that the number is not a perfect square.

Here's an example implementation of the above steps:

import kotlin.math.sqrt

fun main() {
// Step 1: Get the input number
val number = 16

// Step 2: Calculate the square root of the number
val squareRoot = sqrt(number.toDouble())

// Step 3: Check if the square root is an integer
val isPerfectSquare = squareRoot.rem(1) == 0.0

// Step 4: Print the result
if (isPerfectSquare) {
println("$number is a perfect square.")
} else {
println("$number is not a perfect square.")
}
}

In this example, the input number is set to 16. The square root of 16 is 4, which is an integer. Therefore, the output will be "16 is a perfect square."

You can modify the number variable to check different numbers for perfect square properties.

That's it! You now have a step-by-step tutorial on how to check if a number is a perfect square in Kotlin.