Start learning free

LESSON 142 OF 415 · LOOPS & GLOBAL VARIABLES

Sum of Squares in Swift: 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

    SWIFT · LOOPS & GLOBAL VARIABLES

    Sum Of Squares in Swift, explained

    Problem overview

    The method sumOfSquares takes a non-negative integer n and returns the sum of the squares 1 * 1 + 2 * 2 + ... + n * n. For n = 3 the answer is 1 + 4 + 9 = 14.

    Approach: an accumulator

    The method keeps a running total. It starts at 0, a loop visits each number from 1 to n, and each pass adds that number's square to the total. When the loop is done, the total is the answer. Squaring a number is just multiplying it by itself.

    Step by step

    1. Declare the total with var sum = 0. It uses var because it changes in the loop, and Swift infers the type Int.
    2. Loop with for number in 1...n. The closed range includes both ends, so n itself is squared.
    3. Add the square with sum += number * number.
    4. Return sum after the loop.

    The solution in Swift

    class Solution {
        func sumOfSquares(_ n: Int) -> Int {
            var sum = 0
            for number in 1...n {
                sum += number * number
            }
            return sum
        }
    }
    

    The method gives 14 for 3, 1 for 1 and 385 for 10.

    Swift details worth knowing:

    • Closed ranges must be ordered. 1...n requires n to be at least 1. For n = 0 the range would be 1...0, whose upper bound is below its lower bound, and a range like that makes the program crash at run time rather than producing an empty loop. The statement allows 0 (a non-negative integer), so if that input matters, guard against it first: if n < 1 { return 0 }, or use stride(from: 1, through: n, by: 1), which is empty for n = 0.
    • Compound assignment. x += y means x = x + y.
    • Overflow traps. Int is 64 bits and an overflowing operation stops the program with a crash; it doesn't wrap. The total fits for n up to 3,000,000, but 3,200,000 overflows.
    • Loop variable. number is created by the loop and is a constant inside the body.

    Following n = 3

    The total starts at 0. With number equal to 1 it becomes 1. With 2 it becomes 5, and with 3 it becomes 14. After the third pass the range is exhausted, the loop ends, and the method returns 14. Each pass adds exactly one square, so the number of passes equals n.

    Complexity

    Time: O(n). The loop makes n passes, each doing a multiplication and an addition.

    Space: O(1). Only the total and the loop variable are stored.

    A closed formula exists: the sum equals n * (n + 1) * (2 * n + 1) / 6, which gives 55 for n = 5. The loop is simpler to write and to trust, and it is what this lesson practises.

    Edge cases and common mistakes

    • n = 0. The expected answer is 0, but the closed range 1...0 crashes, as described above.
    • n = 1. The range holds one value, and the answer is 1.
    • Starting at 0. It adds 0, which is harmless but unnecessary.
    • Using 1..<n. The loop would skip n, and sumOfSquares(3) would return 5.
    • Adding the number instead of its square. sum += number would return 6 for n = 3.
    • Declaring the total inside the loop. It would reset on each pass.

    Testing

    • sumOfSquares(3) gives 14.
    • sumOfSquares(1) gives 1.
    • sumOfSquares(10) gives 385.
    • sumOfSquares(5) gives 55.
    Keep going with SwiftAbout 340 step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free