A prime number is a positive integer greater than one that has no positive integer divisors other than one and itself. In simpler terms, a prime number is a number that can only be divided evenly by 1 and itself.
For example, 2, 3, 5, 7, 11, and 13 are all prime numbers. On the other hand, 4 is not a prime number because it can be divided evenly by 1, 2, and 4.
Prime numbers play an important role in mathematics and cryptography, as they are used to encrypt and decrypt messages securely. There are infinitely many prime numbers, but they become increasingly rare as the numbers get larger. In fact, there is no known formula for generating all prime numbers, and the discovery of large prime numbers is an ongoing area of research.
fun isPrime(n: Int): Boolean {
if (n <= 1) return false
if (n == 2) return true
if (n % 2 == 0) return false
var i = 3
while (i * i <= n) {
if (n % i == 0) return false
i += 2
}
return true
}
The isPrime
function takes an integer n
as input and returns a boolean value indicating whether n
is prime or not. The function first checks if n
is less than or equal to 1, in which case it immediately returns false
since 1 and all negative numbers are not prime. If n
is equal to 2, the function returns true
, as 2 is the only even prime number.
Next, the function checks if n
is even by checking if its remainder when divided by 2 is 0. If n
is even, the function returns false
since all even numbers greater than 2 are not prime.
Finally, the function checks all odd integers from 3 up to the square root of n
(since any factor of n
greater than the square root of n
must also have a corresponding factor less than the square root of n
). If n
is divisible by any of these odd integers, the function returns false
. Otherwise, it returns true
.
fun isPrime(n: Int): Boolean {
if (n <= 1) return false
if (n == 2) return true
if (n % 2 == 0) return false
var i = 3
while (i * i <= n) {
if (n % i == 0) return false
i += 2
}
return true
}
fun main(){
val n = 17
if (isPrime(n)) {
println("$n is prime")
}
else {
println("$n is not prime")
}
}
This will output “17 is prime” since 17 is indeed a prime number.