Scala function: Determine if a number is prime
Write a Scala function to check if a given number is prime.
Sample Solution:
Scala Code:
object PrimeChecker {
def isPrime(n: Int): Boolean = {
if (n <= 1) {
false
} else if (n <= 3) {
true
} else if (n % 2 == 0 || n % 3 == 0) {
false
} else {
var i = 5
while (i * i <= n) {
if (n % i == 0 || n % (i + 2) == 0) {
return false
}
i += 6
}
true
}
}
def main(args: Array[String]): Unit = {
val number = 13
val isPrimeNumber = isPrime(number)
if (isPrimeNumber) {
println(s"$number is prime.")
} else {
println(s"$number is not prime.")
}
}
}
Sample Output:
13 is prime
Scala Code Editor :
Previous: Calculate the factorial of a number.
Next: Calculate the sum of digits in a number.
What is the difficulty level of this exercise?
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics