Kotlin Program to Display All Prime Numbers from 1 to N


In this article, we will understand how to display all the prime numbers from 1 to N in Kotlin. All possible positive numbers from 1 to infinity are called natural numbers. Prime numbers are special numbers who have only two factors 1 and itself and cannot be divided by any other number.

Below is a demonstration of the same

Suppose our input is −

Value of n :10

The desired output would be −

2 3 5 7

Algorithm

  • Step 1 − Start

  • Step 2 − Declare two integers: low and high

  • Step 3 − Define the integer

  • Step 4 − Using a while loop from low to high, check if the ‘i’ value is divisible by any number from 2 to i.

  • Step 5 − If yes, check the next number

  • Step 6 − If no, store the number as a prime number

  • Step 7 − Display the ‘i’ value as LCM of the two numbers

  • Step 8 − Stop

Example 1

In this example, we will display all Prime Numbers from 1 to N in Kotlin using a for loop:

fun main() { var low = 1 val input = 15 println("The value of N is defined as $input") println("The prime numbers are: ") while (low < input) { if (primeNumber(low)) print(low.toString() + " ") ++low } } fun primeNumber(num: Int): Boolean { var flag = true for (i in 2..num / 2) { if (num % i == 0) { flag = false break } } return flag }

Output

The value of N is defined as 15
The prime numbers are:
1 2 3 5 7 11 13

Example 2

In this example, we will display all Prime Numbers from 1 to N −

fun main() { val input = 10 println("The value of N is defined as $input") printPrimeNumbers(input) } fun printPrimeNumbers(input: Int) { var low = 1 println("The prime numbers are: ") while (low < input) { if (primeNumber(low)) print(low.toString() + " ") ++low } } fun primeNumber(num: Int): Boolean { var flag = true for (i in 2..num / 2) { if (num % i == 0) { flag = false break } } return flag }

Output

The value of N is defined as 10
The prime numbers are:
1 2 3 5 7

Updated on: 13-Oct-2022

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements