Kotlin Program to Check Whether a Number can be Expressed as Sum of Two Prime Numbers

In this tutorial, we will write a Kotlin program to check whether a given number can be expressed as the sum of two prime numbers.

A prime number is a number that is divisible by only 1 and itself. For example, 2, 3, 5, 7, 11, 13, 17, 19, 23, 29 are prime numbers.

Any number that is not a prime number is called a composite number.

To check whether a number can be expressed as the sum of two prime numbers, we will iterate over all possible pairs of prime numbers and check if their sum equals the given number.

We can use the Sieve of Eratosthenes algorithm to generate a list of prime numbers.

Here is the Kotlin program to check whether a number can be expressed as the sum of two prime numbers:

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

fun main() {
    val num = 34
    var flag = false
    for (i in 2..num/2) {
        if (isPrime(i)) {
            val j = num - i
            if (isPrime(j)) {
                println("$num can be expressed as the sum of $i and $j.")
                flag = true
            }
        }
    }
    if (!flag) {
        println("$num cannot be expressed as the sum of two prime numbers.")
    }
}

In this program, the isPrime function checks whether a number is prime or not.

The main function takes a number num as input and iterates over all possible pairs of prime numbers that add up to num.

If such a pair is found, it is printed to the console along with the input number num.

If no such pair is found, a message is printed to the console indicating that num cannot be expressed as the sum of two prime numbers.

We can test this program with various input values to check its correctness.

For example, if we run the program with num = 34, we should see the following output:

34 can be expressed as the sum of 3 and 31.
34 can be expressed as the sum of 5 and 29.
34 can be expressed as the sum of 11 and 23.
34 can be expressed as the sum of 17 and 17.

As we can see, 34 can be expressed as the sum of two prime numbers in four different ways.

If we run the program with a non-prime number like 16, we should see the following output:

16 can be expressed as the sum of 3 and 13.
16 can be expressed as the sum of 5 and 11.
16 cannot be expressed as the sum of two prime numbers.

As we can see, 16 cannot be expressed as the sum of two prime numbers, and the program correctly reports this fact.

In conclusion, we have written a Kotlin program to check whether a given number can be expressed as the sum of two prime numbers.

We have used the Sieve of Eratosthenes algorithm to generate a list of prime numbers and checked all possible pairs of prime numbers to find a pair that adds up to the input number.