English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Kotlin program to check if a number can be expressed as the sum of two prime numbers

Comprehensive Collection of Kotlin Examples

In this program, you will learn how to check if a given number can be expressed as the sum of two prime numbers. This is done through loops and break statements in Kotlin.

To complete this task, the function checkPrime() was created.

If the number passed to the function isprime numberThen checkPrime() returns1

Example: Integer as the sum of two prime numbers

fun main(args: Array<String>) {
    val number = 34
    var flag = false
    for (i in 2..number / 2) {
        //Condition for i to be a prime number
        if (checkPrime(i)) {
            //n-Condition for i to be a prime number
            if (checkPrime(number - i)) {
                // n = primeNumber1 + primeNumber2
                System.out.printf("%d = %d + %d\n", number, i, number - i)
                flag = true
            }
        }
    }
    if (!flag)
        println("$number cannot be expressed as the sum of two prime numbers.")
}
//Function used to check for prime numbers
fun checkPrime(num: Int): Boolean {
    var isPrime = true
    for (i in 2..num / 2) {
        if (num % i == 0) {
            isPrime = false
            break
        }
    }
    return isPrime
}

When running the program, the output is:

34 = 3 + 31
34 = 5 + 29
34 = 11 + 23
34 = 17 + 17

This is the equivalent Java code:Java Program to Represent a Number as the Sum of Two Numbers.

Comprehensive Collection of Kotlin Examples