Home »
Kotlin »
Kotlin Programs »
Kotlin Basic Programs
Kotlin program to find prime numbers in a given range
Kotlin | Find prime number in a range: Here, we are going to learn how to find prime numbers in a given range in Kotlin programming language?
Submitted by IncludeHelp, on April 24, 2020
Problem statement
Given a range start and end, we have to print all prime numbers between start and end (including start and end).
Example:
Input:
start = 1
end = 100
Output:
[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]
Kotlin - Find prime numbers in a given range
A prime number is a natural number that is greater than 1 and cannot be formed by multiplying two smaller natural numbers.
Program to find prime numbers in a given range in Kotlin
/**
* Kotlin Program to find out Prime Numbers between
* given Range(include START and END)
* A prime number is a whole number greater than 1
* whose only factors are 1 and itself.
* e.g 7, 11, 13, 17
*/
package com.includehelp.basic
import java.util.*
//Function to check Prime Number
fun findPrimeNo(number: Long): Boolean {
if(number<2) return false
for (i in 2.toLong()..number/2) {
if (number % i == 0.toLong()) {
return false
}
}
return true
}
//Main Function, Entry Point of Program
fun main(arg: Array<String>) {
//Input Stream
val sc = Scanner(System.`in`)
//Input Start of Range
print("Enter Start of Range : ")
val start: Long = sc.nextLong()
//Input End of Range
print("Enter End of Range : ")
val end: Long = sc.nextLong()
//Declare Mutable List to hold factors
val list: MutableList<Long> = ArrayList()
//iterate through loop start to end to find Prime number in Range
for (i in start..end) {
if (findPrimeNo(i)) {
list.add(i)
}
}
println("Prime Numbers from $start to $end : $list")
}
Output
Run 1:
Enter Start of Range : 1
Enter End of Range : 100
Prime Numbers from 1 to 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]
---
Run 2:
Enter Start of Range : 333
Enter End of Range : 999
Prime Numbers from 333 to 999 : [337, 347, 349, 353, 359, 367, 373,
379, 383, 389, 397, 401, 409, 419, 421, 431, 433, 439, 443, 449, 457,
461, 463, 467, 479, 487, 491, 499, 503, 509, 521, 523, 541, 547, 557,
563, 569, 571, 577, 587, 593, 599, 601, 607, 613, 617, 619, 631, 641,
643, 647, 653, 659, 661, 673, 677, 683, 691, 701, 709, 719, 727, 733,
739, 743, 751, 757, 761, 769, 773, 787, 797, 809, 811, 821, 823, 827,
829, 839, 853, 857, 859, 863, 877, 881, 883, 887, 907, 911, 919, 929,
937, 941, 947, 953, 967, 971, 977, 983, 991, 997]