Scala program to find prime numbers

1. Introduction

Prime numbers are fundamental in the realm of mathematics and computer science. A prime number is a number greater than 1 that cannot be formed by multiplying two smaller natural numbers. This basic concept plays a significant role in areas like cryptography. In this blog post, we will discover how to find prime numbers in a given range using Scala.

2. Program Steps

1. Set up the Scala environment.

2. Create an object to house the main function.

3. Define a range of numbers for which prime numbers will be identified.

4. Implement a function to determine if a number is prime.

5. Iterate over the defined range and identify the prime numbers using the prime-checking function.

6. Print each prime number found.

7. Run the program.

3. Code Program

object PrimeNumberApp {
  def main(args: Array[String]): Unit = {
    // Define a range of numbers
    val range = 2 to 20

    println("Prime numbers in the range 2 to 20 are:")

    // Check each number in the range for primality
    range.foreach { num =>
      if (isPrime(num)) println(num)
    }
  }

  // Function to check if a number is prime
  def isPrime(n: Int): Boolean = {
    if (n <= 1) false
    else if (n == 2) true
    else !(2 until n).exists(x => n % x == 0)
  }
}

Output:

Prime numbers in the range 2 to 20 are:
2
3
5
7
11
13
17
19

Explanation:

1. We start with an object named PrimeNumberApp. In Scala, the main method, which serves as the program's entry point, is located inside an object.

2. Inside the main function, we define a range of numbers between 2 and 20, inclusive.

3. We then print a statement indicating that we will display the prime numbers within this range.

4. The isPrime function holds the logic to determine if a number is prime. It first checks if the number is less than or equal to 1 (in which case it's not prime). If the number is 2, it's prime. Otherwise, it checks if there exists any number between 2 and the number itself (exclusive) that divides the number without a remainder. If such a number exists, then the original number is not prime.

5. We iterate over each number in the range and use the isPrime function to determine if it's prime. If it is, we print the number.

6. As reflected in the output, when executed, the program displays the prime numbers between 2 and 20.


Comments