Kotlin Program:

- To print prime numbers between 1 & N

Example:

User Input: 12

Output: 2,3,5,7,11

import java.util.Scanner

fun prime(n:Int):Boolean{
  if(n<2)return false
  for(i in 2..n/2) {
    if(n%i==0) return false
  }
  return true
}

fun main(args: Array<String>) {
  print("Enter any +ve number : ")
  val userInput = Scanner(System.`in`)
  var num:Int = userInput.nextInt()

  println("Your prime numbers between 1 & $num are :")
  for(i in 2..num-1)
    if(prime(i))print("$i ")
}

Output:

  Enter any +ve number : 20
  Your prime numbers between 1 & 20 are :
  2 3 5 7 11 13 17 19
Program
number

You should know first :

Prime numbers: Numbers greater than 1 & have only 2 factors ( 1 and itself )


Main Logic to check prime :

fun prime(n:Int):Boolean{
  for(i in 2..n/2) {
    if(n%i==0) return false
  }
  return true
}

We are running the loop n/2 Since, any number can have only factors under its half, except itself


To print all primes :

for(i in 2..num-1) {
  //check every number for prime [ if(prime(i)) ], if prime then print the number
}
Concept

Coming Soon !

Quick
Tutorial

Quote

Learn from yesterday, live for today, hope for tomorrow. The important thing is not to stop questioning.