Scala function: Check if a number is a perfect square
Write a Scala function to check if a given number is a perfect square.
Pre-Knowledge (Before you start!)
- Basic Scala Syntax: Familiarity with writing and running Scala programs.
- Mathematical Functions: Knowledge of using mathematical functions like sqrt from the math library.
- Type Conversion: Understanding how to convert between numeric types, such as Double to Int.
- Boolean Logic: Ability to use Boolean values and conditions to determine outcomes.
- Printing Output: Familiarity with the println() function to display output on the screen.
Hints (Try before looking at the solution!)
- Define the Function: Create a function named "isPerfectSquare" that takes an integer as input and returns a Boolean indicating whether the number is a perfect square.
- Calculate the Square Root: Use the math.sqrt() function to calculate the square root of the number. Convert the result to an integer using toInt.
- Check for Perfect Square: Multiply the integer square root by itself and compare it to the original number. If they are equal, return true; otherwise, return false.
- Call the Function: In the main method, test the "isPerfectSquare" function by passing different integers, such as 36 and 19.
- Display the Output: Use println() to print whether each number is a perfect square, including the result in the output message.
- Test with Different Numbers: Change the input values to verify the program works for various cases, including edge cases like 0, 1, and negative numbers.
- Common Errors to Avoid:
- Forgetting to convert the square root to an integer, leading to incorrect comparisons.
- Misplacing the comparison logic, causing incorrect results for perfect squares.
- Not handling edge cases like negative numbers, which cannot be perfect squares.
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?
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics