1. Overview

Calculating the sum of natural numbers has many practical use cases in fields such as mathematics, computer science, etc.

In this tutorial, we’ll explore various ways to calculate the sum of the first N natural numbers in Kotlin.

2. Using Loops

In this section, let’s learn how to use loop constructs to solve our use case.

2.1. for Loop

Let’s write the sumUsingForLoop() function that uses a for loop to iterate over the first n natural numbers for computing the sum:

fun sumUsingForLoop(n: Int): Int {
    var sum = 0
    for (i in 1..n) {
        sum += i
    }
    return sum
}

Now, let’s test our function:

Assertions.assertEquals(15, sumUsingForLoop(5))
Assertions.assertEquals(5050, sumUsingForLoop(100))

Great! We got this one right.

2.2. while Loop

Similar to the for loop approach, let’s write the sumUsingWhileLoop() function that uses a while loop instead:

fun sumUsingWhileLoop(n: Int): Int {
    var sum = 0
    var i = 1
    while (i <= n) {
        sum += i
        i++
    }
    return sum
}

Like earlier, let’s verify our function:

Assertions.assertEquals(15, sumUsingWhileLoop(5))
Assertions.assertEquals(5050, sumUsingWhileLoop(100))

It works as expected.

3. Using Arithmetic Progression Formula

The first N natural numbers form an arithmetic progression, so we can directly use the well-known arithmetic formula to find the sum:

sum = N*(N+1)/2

Now, we can write a one-line statement in our sumUsingArithmeticProgressionFormula() function to calculate the sum:

fun sumUsingArithmeticProgressionFormula(n: Int): Int {
    return (n * (n + 1)) / 2
}

Lastly, let’s see it in action:

Assertions.assertEquals(15, sumUsingArithmeticProgressionFormula(5))
Assertions.assertEquals(5050, sumUsingArithmeticProgressionFormula(100))

4. Using Extension Functions for Range

In this section, we’ll explore a set of extension functions with ranges to calculate the sum.

4.1. With sum()

Let’s write the sumUsingRangeAndSum() function that uses the sum() extension function for the inclusive range 1..n to calculate the sum:

fun sumUsingRangeAndSum(n: Int): Int {
    return (1..n).sum()
}

Now, let’s verify that it’s working correctly:

Assertions.assertEquals(15, sumUsingRangeAndSum(5))
Assertions.assertEquals(5050, sumUsingRangeAndSum(100))

Great! It works!

4.2. With sumBy()

We can also use the sumBy() extension function. Let’s go ahead and use it in the sumUsingRangeAndSumBy() function:

fun sumUsingRangeAndSumBy(n: Int): Int {
    return (1..n).sumBy { it }
}

It’s interesting to note that we used the it identifier to specify that we must use each element within the range for the sum.

Next, let’s check that it’s giving the right results:

Assertions.assertEquals(15, sumUsingRangeAndSumBy(5))
Assertions.assertEquals(5050, sumUsingRangeAndSumBy(100))

4.3. With fold()

Now, let’s use the fold extension function within the sumUsingRangeAndFold() function to find the sum:

fun sumUsingRangeAndFold(n: Int): Int {
    return (1..n).fold(0) { acc, num -> acc + num }
}

We must note the initial value of the accumulator (acc) is 0, and we add each number (num) to update the accumulator value.

Like earlier, let’s verify our function:

Assertions.assertEquals(15, sumUsingRangeAndFold(5))
Assertions.assertEquals(5050, sumUsingRangeAndFold(100))

4.4. With reduce()

Let’s see how we can write the sumUsingRangeAndReduce() function that uses the reduce() extension function on (1..n):

fun sumUsingRangeAndReduce(n: Int): Int {
    return (1..n).reduce { acc, num -> acc + num }
}

It’s worth noting that reduce() is almost similar to fold(), except that the initial value is set as the first member of the range.

Further, let’s see this in action:

Assertions.assertEquals(15, sumUsingRangeAndReduce(5))
Assertions.assertEquals(5050, sumUsingRangeAndReduce(100))

5. Using Sequence

Let’s write the sumUsingSequence() function that generates a sequence of natural numbers and takes only the first n numbers for applying the sum() function:

fun sumUsingSequence(n: Int): Int {
    return generateSequence(1) { it + 1 }
      .take(n)
      .sum()
}

We must note that we used the generateSequence() function to generate the sequence with an initial value of 1 and a lambda function {it + 1} to calculate the next value.

Now, we should also test this approach:

Assertions.assertEquals(15, sumUsingSequence(5))
Assertions.assertEquals(5050, sumUsingSequence(100))

Fantastic! It looks like we nailed this one.

6. Using Recursion

For our use case, recursion seems like a good candidate. So, let’s go ahead and write the sumUsingRecursion() function for the solution:

fun sumUsingRecursion(n: Int): Int {
    return if (n <= 1) {
        n
    } else {
        n + sumUsingRecursion(n - 1)
    }
}

Further, let’s check our solution by writing a few tests:

Assertions.assertEquals(15, sumUsingRecursion(5))
Assertions.assertEquals(5050, sumUsingRecursion(100))

Great! It works!

7. Conclusion

In this article, we learned several approaches, such as loops, extension functions, recursion, and sequences, to calculate the sum of the first N natural numbers in Kotlin.

As always, the code from this article is available over on GitHub.

Comments are open for 30 days after publishing a post. For any issues past this date, use the Contact form on the site.