w3resource

Scala function: Check if a number is a perfect square

Scala Function Exercise-9 with Solution

Write a Scala function to check if a given number is a perfect square.

Sample Solution:

Scala Code:

object SquareChecker {
  def isPerfectSquare(number: Int): Boolean = {
    val sqrt = math.sqrt(number).toInt
    sqrt * sqrt == number
  }

  def main(args: Array[String]): Unit = {
    val number1 = 36
    val number2 = 19

    println(s"Is $number1 is a perfect square? ${isPerfectSquare(number1)}")
    println(s"Is $number2 is a perfect square? ${isPerfectSquare(number2)}")
  }
}

Sample Output:

Is 36 is a perfect square? true
Is 19 is a perfect square? false

Scala Code Editor :

Previous: Check if a number is even.
Next: Check if a list is sorted.

What is the difficulty level of this exercise?



Follow us on Facebook and Twitter for latest update.