Write a Kotlin program to print prime numbers between interval a and b, assuming a < b
Example
Input a = 10, b = 20 Output 11 13 17 19
1. Program to print prime numbers between interval
Pseudo Algorithm –
- Check conditions for valid range. b must be greater than or equal to a.
- Run a loop from a to b
- Check for each value between a and b whether it is prime or not. If yes, print it. Otherwise, check for next value.
Sourcecode –
import java.util.* import kotlin.math.sqrt fun main() { val read = Scanner(System.`in`) println("Enter a:") val a = read.nextInt() println("Enter b:") val b = read.nextInt() if(b < a) { println("Invalid Range a > b") } else { for(i in a..b) { if(checkPrime(i)) { print("$i ") } } } } private fun checkPrime(n: Int): Boolean { // Number less than or equal 1 is not prime if(n <= 1) return false // 2 is only even prime number if(n == 2) return true // Check if number (> 2) is even. If yes, it is not prime. if(n % 2 == 0) return false var flag = true val root = sqrt(n.toDouble()).toInt() // We need to check till square root of n only to find whether n is prime. for(i in 3..root step 2) { if((n % i) == 0) { flag = false break } } return flag }
When you run the program, output will be –
Enter a: 1 Enter b: 100 2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97
Explanation:
As per pseudo algorithm, we checked for each value between a and b for prime number.
- If a > b, it means range is not value. So, we print error message.
- Otherwise, we run a loop from a to b.
- Then, we check whether current value is prime or not.
- Logic for prime has been explained in previous post. You can go through it to know how it works.
Thus, we went through Kotlin Program to print prime numbers between given interval.