Write a Kotlin Program to check whether number is prime or not.
For example,
Input 12 Output 12 is not prime
Input 13 Output 13 is prime
1. Program to Check Whether Number is prime or not
Now, we will check whether number is prime or not using for loop
Sourcecode –
fun main() { val read = Scanner(System.`in`) println("Enter n:") val n = read.nextInt() if(checkPrime(n)) println("$n is prime") else println("$n is not prime") } 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 n: 101 101 is prime
Explanation:
Here, we have created an object of Scanner. Scanner takes an argument which says where to take input from.
System.`in` means take input from standard input – Keyboard.
read.nextInt() means read anything (i.e. Int value) entered by user before space or line break from standard input – Keyboard.
We stored entered value in variable n
We defined a function checkPrime that returns true if n is prime else it returns false.
Inside checkPrime function,
- If n <= 1 , it's not a prime number. So, returns false.
- If n == 2, it only even prime number. So, returns true.
- Then, we check if n is even or not. Not that this will be checked only if above two conditions are false. If n is even, it’s not prime number. So, returns false.
- Now, we know this number is not even and greater than 2. Also, we need to check conditions till square root only. So, we find square root of n and stored in variable root
- Then, we run a loop from 3 to square root. Note that we have increased the loop by step 2. That’s because we do not need to check for even number. We already know that n is not even.
- If at value of i, n is divisible, it means it is not prime. So, we set flag to false and break the loop
- Finally, we return value of flag (Either true or false).
Thus, we went through Kotlin Program to check whether number is prime or not.