Kotlin Program to find the sum of prime numbers between 1 to n
In this program, You will learn how to find the sum of prime numbers between 1 to n in Kotlin.
10th: 2 + 3 + 5 + 7 => 17
Example: How to find the sum of prime numbers between 1 to n in Kotlin.
import java.util.Scanner
fun main(args: Array<String>) {
var n: Int
var s = 0
var sc = Scanner(System.`in`)
print("Enter a number:")
n = sc.nextInt()
for (i in 2..n) {
var p = 1
var k = 2
while (k < i) {
if (i % k == 0) {
p = 0
break
}
k++
}
if (p == 1) {
s += i
}
}
println("Sum of prime numbers:$s")
}
Output:
Enter a number:10
Sum of prime numbers:17