AlgoViz

Arithmetic sequences

easy 13 min

An arithmetic sequence adds the same difference d at every step, like stairs of equal height.

Video lesson · Chapter 1 of 5

A staircase of light

0:00 / 4:24

Arithmetic sequences

1:24Reel

Read caption

Pia tests each pair among six radio stations and counts fifteen links without repeating one. One fewer each row still adds to quadratic work.

How it works

Step through the idea, or press Play.

Step 1 of 3

Add the same difference. Every term is the previous one plus a fixed d, so the terms climb (or fall) like equal stairs

Understand it

Start here

What an arithmetic sequence is

An arithmetic sequence (also called an arithmetic progression, or AP) is a list of numbers where each term differs from the one before by the same common difference dd. In 2,5,8,11,14,…2, 5, 8, 11, 14, \dots the first term is a1=2a_1 = 2 and d=3d = 3. Think of climbing stairs where every step is the same height.

The defining rule

ak+1=ak+de.g. 2→+35→+38→+311a_{k+1} = a_k + d \qquad\text{e.g. } 2 \xrightarrow{+3} 5 \xrightarrow{+3} 8 \xrightarrow{+3} 11
One rule fixes the whole sequence once you know where it starts (a1a_1) and how far each step moves (dd).
  • Loop complexity

    Nested loops like for j in range(i) run 0+1+⋯+(n−1)0 + 1 + \dots + (n-1) times: an arithmetic sum.

  • O(1) sums

    Replace a summing loop with n(n+1)2\frac{n(n+1)}{2} and drop from O(n)O(n) to O(1)O(1).

  • Array problems

    Evenly spaced values, arithmetic slices, and missing terms all lean on the same two formulas.

Formula 1

The nth term

Jump straight to term n

an=a1+(n−1) da_n = a_1 + (n - 1)\,d
a1a_1 is where you start, n−1n - 1 is the number of jumps, and dd is the size of each jump. For 2,5,8,…2, 5, 8, \dots: a10=2+9×3=29a_{10} = 2 + 9 \times 3 = 29.
Climbing from a₁ to a₅ in 2, 5, 8, ...
  1. 12a₁, 0 jumps
  2. 25a₂, 1 jump
  3. 38a₃, 2 jumps
  4. 411a₄, 3 jumps
  5. 514a₅, 4 jumps

Five landings, four stairs. Term $n$ is always $n - 1$ jumps from the start.

Python
def nth_term(a1, d, n):    return a1 + (n - 1) * ddef nth_term_slow(a1, d, n):    term = a1    for _ in range(n - 1):        term += d    return termprint(nth_term(2, 3, 10))            # 29print(nth_term_slow(2, 3, 10))       # 29, after 9 additionsprint(nth_term(10, -3, 6))           # -5: d can be negativeprint(nth_term(2, 3, 1_000_000))     # 2999999, instantly
The formula is O(1). Walking term by term is O(n).
Edit and run it in your browser

Formula 2

The sum: Gauss's pairing trick

The story goes that young Gauss's teacher told the class to add 11 to 100100. While the others added one number at a time, Gauss wrote 5050 almost at once. His trick: pair the first number with the last. 1+100=2+99=3+98=1011 + 100 = 2 + 99 = 3 + 98 = 101, and there are 50 such pairs.

Pairing first with last

Moving inward adds 1 to the small number and takes 1 from the big one, so every pair has the same sum.

Sum of the first n terms

Sn=n (a1+an)2=n2(2a1+(n−1) d)S_n = \frac{n\,(a_1 + a_n)}{2} = \frac{n}{2}\bigl(2a_1 + (n-1)\,d\bigr)
Number of terms times the average of the first and last. For 2,5,…,292, 5, \dots, 29: S10=10×312=155S_{10} = \frac{10 \times 31}{2} = 155. The second form substitutes an=a1+(n−1)da_n = a_1 + (n-1)d when you do not know the last term.

Quick reference

FormulaPurposeExample
a1+(n−1)da_1 + (n-1)dnth term2+9×3=292 + 9 \times 3 = 29
n(a1+an)2\frac{n(a_1 + a_n)}{2}Sum of n terms10×312=155\frac{10 \times 31}{2} = 155
n(n+1)2\frac{n(n+1)}{2}Sum of 1 to n100×1012=5050\frac{100 \times 101}{2} = 5050
n(n−1)2\frac{n(n-1)}{2}Sum of 0 to n - 1Nested loop count: O(n2)O(n^2)

Derivation

Why the sum formula works

Gauss's pairing works for any arithmetic sequence, odd length included, if you write the sum twice: once forwards and once backwards. Then add the two rows column by column.

Write it twice and add

S=a1+a2+⋯+anS=an+an−1+⋯+a12S=(a1+an)+(a1+an)+⋯+(a1+an)⏟n columns\begin{aligned} S &= a_1 + a_2 + \dots + a_n \\ S &= a_n + a_{n-1} + \dots + a_1 \\ \hline 2S &= \underbrace{(a_1 + a_n) + (a_1 + a_n) + \dots + (a_1 + a_n)}_{n \text{ columns}} \end{aligned}
Each column sums to a1+ana_1 + a_n: one step right adds dd on top and removes dd below. So 2S=n(a1+an)2S = n(a_1 + a_n) and S=n(a1+an)2S = \frac{n(a_1 + a_n)}{2}.

The special case 1 + 2 + ... + n

1+2+⋯+n=n(n+1)20+1+⋯+(n−1)=n(n−1)21 + 2 + \dots + n = \frac{n(n+1)}{2} \qquad 0 + 1 + \dots + (n-1) = \frac{n(n-1)}{2}
Set a1=1a_1 = 1, an=na_n = n for the first; a1=0a_1 = 0, an=n−1a_n = n - 1 for the second. Both are about n22\frac{n^2}{2}.

Complexity

Why nested loops are O(n²)

Python
def count_pairs(n):    count = 0    for i in range(n):        for j in range(i):     # runs 0, 1, 2, ..., n - 1 times            count += 1    return countfor n in [5, 10, 100]:    print(n, count_pairs(n), n * (n - 1) // 2)# 5 10 10# 10 45 45# 100 4950 4950
The inner loop runs i times, so the total is 0 + 1 + ... + (n - 1).
Edit and run it in your browser

From a loop to a Big O class

Recognise the arithmetic sequence of inner counts, sum it, then keep only the fastest-growing term.

Exact count to Big O

∑i=0n−1i=n(n−1)2=n22−n2=O(n2)\sum_{i=0}^{n-1} i = \frac{n(n-1)}{2} = \frac{n^2}{2} - \frac{n}{2} = O(n^2)
For n=5n = 5 that is 10 iterations; for n=1000n = 1000 it is 499,500. Doubling nn roughly quadruples the count.

The triangle is about half the square

nn(n−1)2\frac{n(n-1)}{2}n2n^2ratio
510250.40
10451000.45
1004,95010,0000.495
1,000499,5001,000,0000.4995
Draw the n×nn \times n grid of (i,j)(i, j) pairs: the loop fills the cells below the diagonal, and the ratio approaches 12\frac12.

Pattern spotting

Loop shapes and their sums

Inner loop inside for i in range(n)Inner countsTotalClass
for j in range(i)0,1,…,n−10, 1, \dots, n-1n(n−1)2\frac{n(n-1)}{2}O(n2)O(n^2)
for j in range(i + 1)1,2,…,n1, 2, \dots, nn(n+1)2\frac{n(n+1)}{2}O(n2)O(n^2)
for j in range(i + 1, n)n−1,…,1,0n-1, \dots, 1, 0n(n−1)2\frac{n(n-1)}{2}O(n2)O(n^2)
for j in range(n)n,n,…,nn, n, \dots, nn2n^2O(n2)O(n^2)
for j in range(0, i, 2)about i2\frac{i}{2}about n24\frac{n^2}{4}O(n2)O(n^2)
j = 1; while j < i: j *= 2about log⁡2i\log_2 iabout nlog⁡2nn \log_2 nO(nlog⁡n)O(n \log n)
If the inner count rises or falls by a constant each pass, it is an arithmetic sum and the loop is quadratic.

Is this nested loop quadratic?

Adding a constant gives an arithmetic sum. Multiplying gives a geometric one, which behaves very differently.

Where the triangle hides

  • Bubble sort

    Pass kk compares n−kn - k neighbours: (n−1)+⋯+1=n(n−1)2(n-1) + \dots + 1 = \frac{n(n-1)}{2}.

  • Selection sort

    Finding the minimum of a shrinking suffix: the same triangle of comparisons.

  • All pairs

    Comparing every pair of nn items once gives (n2)=n(n−1)2\binom{n}{2} = \frac{n(n-1)}{2} pairs.

In code

Checking for an arithmetic sequence

Is this array arithmetic?

One pass, O(n)O(n). If the question allows rearranging the values, sort first: O(nlog⁡n)O(n \log n).
Python
def is_arithmetic(arr):    if len(arr) < 2:        return True    d = arr[1] - arr[0]    return all(arr[i] - arr[i - 1] == d for i in range(2, len(arr)))def count_arithmetic_slices(arr):    count = curr = 0    for i in range(2, len(arr)):        if arr[i] - arr[i - 1] == arr[i - 1] - arr[i - 2]:            curr += 1          # slices ending here grow by one            count += curr        else:            curr = 0    return countprint(is_arithmetic([2, 5, 8, 11]))           # Trueprint(count_arithmetic_slices([1, 2, 3, 4]))  # 3: [1,2,3], [2,3,4], [1,2,3,4]
Counting arithmetic slices (contiguous runs of 3 or more with one difference) reuses the arithmetic sum.
Edit and run it in your browser

Slices in a run of k equal-difference elements

1+2+⋯+(k−2)=(k−1)(k−2)21 + 2 + \dots + (k-2) = \frac{(k-1)(k-2)}{2}
A run of kk elements holds k−2k - 2 slices of length 3, k−3k - 3 of length 4, and so on down to one of length kk. For k=4k = 4: 3 slices.

Edge cases

Negative, zero and huge

  • Negative d is fine

    10,7,4,1,−2,…10, 7, 4, 1, -2, \dots has d=−3d = -3. Both formulas still work: a6=10+5(−3)=−5a_6 = 10 + 5(-3) = -5.

  • d = 0 is an AP too

    4,4,4,44, 4, 4, 4 is arithmetic with d=0d = 0; the sum is just n×a1n \times a_1.

  • Integer overflow

    In Java or C++, n(n+1)n(n+1) overflows a 32-bit int past n≈46,340n \approx 46{,}340. Widen to 64 bits first.

Safe sum code

  • Python: n * (n + 1) // 2 stays an exact integer.
  • Java: (long) n * (n + 1) / 2 widens before multiplying.
  • Or halve whichever of nn and n+1n + 1 is even, then multiply.

Risky sum code

  • Python: n * (n + 1) / 2 returns a float and loses precision for huge nn.
  • Java: int arithmetic overflows silently.
  • (n / 2) * (n + 1) with integer division is wrong when nn is odd.

In the wild

Where arithmetic sequences show up

  • Memory addresses

    Element ii of an array lives at base+i×size\text{base} + i \times \text{size}: an arithmetic sequence of addresses.

  • Pagination

    Page pp starts at offset (p−1)×pageSize(p - 1) \times \text{pageSize}, the nth-term formula exactly.

  • Linear backoff

    Retry after 1 s, 2 s, 3 s, ...: the total wait after kk retries is k(k+1)2\frac{k(k+1)}{2} seconds.

  • Handshake counts

    nn services that each talk to every other need n(n−1)2\frac{n(n-1)}{2} connections.

Recap

Key takeaways

Key points

  • An arithmetic sequence adds the same difference dd each step; dd can be negative or zero.
  • nth term: an=a1+(n−1)da_n = a_1 + (n - 1)d. It takes n−1n - 1 jumps, not nn.
  • Sum: Sn=n(a1+an)2S_n = \frac{n(a_1 + a_n)}{2}, the number of terms times the average of first and last.
  • 1+2+⋯+n=n(n+1)21 + 2 + \dots + n = \frac{n(n+1)}{2}, so 1+⋯+100=50501 + \dots + 100 = 5050 in O(1)O(1).
  • A loop with for j in range(i) runs n(n−1)2\frac{n(n-1)}{2} times: O(n2)O(n^2).
  • Use // in Python and 64-bit integers in Java or C++ for these sums.

Sources