In this tutorial, you shall learn how to find the sum of squares of first n natural numbers in Kotlin, using the formula or a loop statement, with example programs.
Kotlin – Sum of squares of first N natural numbers
To find the sum of squares of first n natural numbers in Kotlin, we can use the formula or a looping statement.
The formula to find the sum of squares of first n natural numbers is
n * ( n + 1 ) * ( 2 * n + 1) / 6
Program with Formula
In the following program, we read n
from user and find the sum of squares of first n natural numbers using the specified formula.
Main.kt
fun main() {
print("Enter n : ")
val n = readLine()!!.toInt()
val sum = n * (n + 1) * (2*n + 1) / 6
print("Sum of squares of first $n natural numbers is $sum")
}
Output #1
Enter n : 6
Sum of squares of first 6 natural numbers is 91
Output #2
Enter n : 10
Sum of squares of first 10 natural numbers is 385
Related tutorials for the above program
Program with Looping statement
In the following program, we read n
from user and find the sum of first n natural numbers using For loop statement.
Main.kt
fun main() {
print("Enter n : ")
val n = readLine()!!.toInt()
var sum = 0
for (i in 1..n) {
sum += i * i
}
print("Sum of squares of first $n natural numbers is $sum")
}
Output #1
Enter n : 6
Sum of squares of first 6 natural numbers is 91
Output #2
Enter n : 10
Sum of squares of first 10 natural numbers is 385
Related tutorials for the above program
Conclusion
In this Kotlin Tutorial, we learned how to find the sum of squares of first n natural numbers.