Reference Materials
Certification Courses
Created with over a decade of experience and thousands of feedback.
Python online compiler
JavaScript online compiler
SQL online compiler
Java online compiler
HTML online compiler
C online compiler
C++ online compiler
C# online compiler
PHP online compiler
Swift online compiler
Kotlin online compiler
TypeScript online compiler
Go online compiler
Rust online compiler
Scala online compiler
Dart online compiler
R online compiler
Ruby online compiler
Kotlin Program to Check Whether a Number can be Expressed as Sum of Two Prime Numbers
In this program, you'll learn to check whether a given number can be expressed as a sum of two prime numbers or not. This is done with the help of loops and break statements in Kotlin.
To accomplish this task, checkPrime() function is created.
The checkPrime() returns 1 if the number passed to the function is a prime number.
Example: Integer as a 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)) {
// condition for n-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 to check prime number
fun checkPrime(num: Int): Boolean {
var isPrime = true
for (i in 2..num / 2) {
if (num % i == 0) {
isPrime = false
break
}
}
return isPrime
}
When you run the program, the output will be:
34 = 3 + 31 34 = 5 + 29 34 = 11 + 23 34 = 17 + 17
Here's the equivalent Java code: Java Program to Repesent a Number as a sum of two numbers.
Did you find this article helpful?