Kotlin: Print Prime Numbers in a Given Range

🎓 Top 15 Udemy Courses (80-90% Discount): My Udemy Courses - Ramesh Fadatare — All my Udemy courses are real-time and project oriented courses.

▶️ Subscribe to My YouTube Channel (178K+ subscribers): Java Guides on YouTube

▶️ For AI, ChatGPT, Web, Tech, and Generative AI, subscribe to another channel: Ramesh Fadatare on YouTube

1. Introduction

Prime numbers are an intriguing part of the mathematical world, playing fundamental roles in areas like cryptography and number theory. By definition, a prime number is a number greater than 1 that has no positive divisors other than 1 and itself. In this post, we'll explore a Kotlin program that efficiently prints prime numbers in a specified range.

2. Program Overview

Our Kotlin exploration will:

1. Obtain a range from the user.

2. Traverse the range to detect prime numbers.

3. Display the prime numbers to the user.

3. Code Program

import java.util.Scanner

fun main() {
    // Utilize Scanner for user input
    val reader = Scanner(System.in)

    // Get the range from the user
    print("Enter the start of the range: ")
    val start = reader.nextInt()
    print("Enter the end of the range: ")
    val end = reader.nextInt()

    // Loop through the range and print prime numbers
    for (num in start..end) {
        if (isPrime(num)) {
            print("$num ")
        }
    }
}

fun isPrime(n: Int): Boolean {
    if (n <= 1) return false
    for (i in 2..Math.sqrt(n.toDouble()).toInt()) {
        if (n % i == 0) return false
    }
    return true
}

Output:

Enter the start of the range: 10
Enter the end of the range: 50
11 13 17 19 23 29 31 37 41 43 47 

4. Step By Step Explanation

1. Scanner Invocation: We begin with creating Scanner class to capture of user input. We've named our instance reader.

2. Range Acquisition: Users are prompted to input the start and end of a range.

3. Prime Number Detection: The program then sifts through each number in the range, calling the isPrime function to verify its primality.

4. isPrime Function:

  • If the number is less than or equal to 1, it's not prime.
  • If the number is greater than 1, the program checks for factors other than 1 and the number itself. The loop to check for factors runs until the square root of the number, a mathematical optimization to reduce the number of checks needed.
  • If no factors are found, the number is prime.

5. Displaying Prime Numbers: As the program identifies prime numbers, they're printed out, granting the user an immediate view of the prime numbers within the specified bounds.

My Top and Bestseller Udemy Courses. The sale is going on with a 70 - 80% discount. The discount coupon has been added to each course below:

Comments

Spring Boot 3 Paid Course Published for Free
on my Java Guides YouTube Channel

Subscribe to my YouTube Channel (165K+ subscribers):
Java Guides Channel

Top 10 My Udemy Courses with Huge Discount:
Udemy Courses - Ramesh Fadatare