Write a Kotlin Program to Express number as Sum of Two Prime Numbers

For example,

Input: 13 Output: 2 + 11

Input: 20 Output: 3 + 17 7 + 13

20 can be expressed as sum of (3 and 17) or (7 and 13).

Input: 4 Output: 2 + 2

Similarly, there is possibility for other numbers as well to be expressed as sum of two primes.

## 1. Program to Express as Sum of Two Prime Numbers

###### Pseudo Algorithm –

- For any value n, run a loop from 2 to n/2.
- Check if i is prime or not.
- If yes, check if n-i is prime or not. If yes, n can be expressed as sum of i and (n-i).
- If no, continue for other value of i.

Sourcecode –

import java.util.* import kotlin.math.sqrt fun main() { val read = Scanner(System.`in`) println("Enter n:") val n = read.nextInt() if(n < 4) { println("$n can not be expressed as sum of two primes") } else { println("$n as sum of two primes: ") for(i in 2..(n/2)) { if(isPrime(i) && isPrime(n-i)) { print("$n = $i + " + (n-i) + "\n") } } } } private fun isPrime(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: 50 50 as sum of two primes: 50 = 3 + 47 50 = 7 + 43 50 = 13 + 37 50 = 19 + 31

###### 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.nextIn()** means read anything entered by user before space or line break from standard input – Keyboard.

Store value read by nextInt() in variable **n**.

Then,

- Check if n is less than 4. If yes, then, it can not be expressed as sum of two primes. we have only two prime numbers, (2 and 3) whose sum is 5, below 4.
- If it is greater than or equal to 4, then we run a loop from 2 to n/2.
- We then check if i and (n-i) are primes or not. If yes, n can be expressed as sum of i and n-i.

Let’s take an example,

n = 5

n > 4. So, else block will be executed.

Now, run a loop from 2 to 2 (5/2 = 2).

At i = 2,

- We check if 2 is prime or not. Since 2 is prime, we check if 5-2 (= 3) is prime or not.
- Since 3 is prime, 5 can be expressed as sum of two primes: 2 + 3

Thus, we went through Kotlin program to express a number as sum of two prime numbers