1. Introduction
A prime number is a number greater than 1 that cannot be formed by multiplying two smaller natural numbers. In computing, it's a common task to determine if a given number is prime. In this blog post, we'll explore a Scala program that checks if a number is prime.
2. Program Steps
1. Create an object to hold the main function.
2. Define a function isPrime that takes an integer n.
3. If n is less than 2, return false.
4. Check divisibility from 2 up to the square root of n.
5. If any number divides n, return false, else return true.
6. Call the function with desired input and print the result.
3. Code Program
object PrimeCheckerApp {
def main(args: Array[String]): Unit = {
val number = 29
if (isPrime(number)) println(s"$number is a prime number.")
else println(s"$number is not a prime number.")
}
// Function to check if a number is prime
def isPrime(n: Int): Boolean = {
if (n < 2) return false
for (i <- 2 to Math.sqrt(n).toInt) {
if (n % i == 0) return false
}
true
}
}
Output:
29 is a prime number.
Explanation:
1. The program starts by defining an object PrimeCheckerApp which contains the main function.
2. Inside this object, a function isPrime is defined. If the number n is less than 2, it returns false indicating it's not a prime number.
3. The function then checks divisibility from 2 up to the square root of n for optimization purposes. If any number within this range divides n, it returns false.
4. If the number is not divisible by any other number in the given range, it's prime, so the function returns true.
5. In the main function, we've chosen 29 as our test input. Depending on the result of isPrime, an appropriate message is printed on the console.
Comments
Post a Comment