Start learning free

LESSON 137 OF 348 · LOOPS & GLOBAL VARIABLES

Sum of Squares in Kotlin: Accumulating with a for Loop

Practice Read the full explanation

Given a non-negative integer n, compute and return the sum of
12 + 22 + 32 + ... + n2

Example:

Input: n = 3

Output: 14

Explanation:
12 + 22 + 32 = 1 + 4 + 9 = 14
Hints:

Where should we store this sum as we compute it?

We can use a variable sum, initially equal to 0. We have to iterate through the numbers 1 to n. How can we do this?

Let's use a for loop and a variable i to iterate through the numbers 1 to n. What should we do inside this loop?

Inside the loop, all we should do is add i * i to sum.
When the loop terminates, the answer lies in sum.

STEP 1 OF 4
    Ctrl + Enter to check

    KOTLIN · LOOPS & GLOBAL VARIABLES

    Sum Of Squares in Kotlin, explained

    Problem overview

    The function sumOfSquares receives a non-negative Int named n and returns 1² + 2² + 3² + ... + n². For n = 3 that is 1 + 4 + 9, which is 14.

    Approach: keep a running total

    The task is a sum of terms that all follow one pattern, the square of a counter. The standard method is an accumulator:

    1. start a total at zero;
    2. visit each number from 1 to n;
    3. add that number's square to the total;
    4. return the total when the numbers run out.

    That's one pass over n numbers, with a constant amount of memory. A closed formula exists, n * (n + 1) * (2 * n + 1) / 6, but this lesson practises loops, so it builds the sum from the individual squares.

    Step by step

    1. Declare the total. var sum = 0 uses var because the value changes inside the loop. Zero is the right start, since nothing has been added yet. Kotlin infers the type Int.
    2. Loop from 1 to n. Use for (i in 1..n). The .. range includes both ends, so n itself gets visited. 1 until n would stop at n - 1.
    3. Add the square. Inside the loop, sum += i * i multiplies i by itself and adds the product to the total. The operator += is shorthand for sum = sum + i * i.
    4. Return the total after the loop, when every square has been added.

    The solution in Kotlin

    class Solution {
        fun sumOfSquares(n: Int): Int {
            var sum = 0
            for (i in 1..n) {
                sum += i * i
            }
            return sum
        }
    }
    

    Kotlin details to know:

    • No power operator. Kotlin has no ** operator for powers. Multiplying i * i is the simple way.
    • Empty ranges. If n is 0, the range 1..0 is empty. Kotlin ranges only count upward, so the loop does nothing and the function returns 0, which is the correct sum of no terms.
    • The loop variable. i is read-only inside the loop body, and the loop supplies the next value on each pass.
    • Int arithmetic is 32-bit. Results past 2,147,483,647 wrap around to negative numbers with no error. This matters here, because squares grow fast (see below).

    Tracing n = 3

    The table shows the loop for the example.

    ii * isum after the pass
    111
    245
    3914

    After the third pass the range is used up, the loop ends and the function returns 14. The same code handles any n: only the number of passes changes, never the shape of the work. If a result looks wrong, tracing a tiny input like this one by hand shows which step misbehaves.

    Complexity

    Time: O(n). The loop runs n times, and each pass does one multiplication and one addition.

    Space: O(1). Only sum and the loop variable are stored, whatever the size of n.

    Edge cases and common mistakes

    • n = 0. The result is 0, produced by the empty loop.
    • n = 1. The result is 1.
    • Off-by-one in the range. 1 until n leaves out n². For n = 3 it would return 5 instead of 14.
    • Starting the range at 0. It's harmless, since 0 * 0 adds nothing, but it does one pointless pass.
    • Adding i instead of i * i. That computes 1 + 2 + 3 = 6 for n = 3, the plain sum.
    • Overflow. The correct sum for n = 1860 is 2,146,682,110, which just fits in an Int. For n = 1861 the true sum is larger than the maximum, and the function returns the wrapped-around value -2144821865. For n = 2000 it returns -1626300296. Using a Long for sum and the product would delay the problem to much larger inputs.

    Testing

    • n = 3 gives 14.
    • n = 0 gives 0.
    • n = 1 gives 1.
    • n = 10 gives 385.
    Keep going with KotlinAbout 340 step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free