Multiplication table

Easy TimeO(n²) SpaceO(n²)

Given a size n, return the n × n multiplication table as an array of n rows, each row an array of n numbers. The value at row i, column j is i × j, with rows and columns both counting from 1. Every row holds the same count of values, so the result is square rather than triangular.

Examples

Example 1

Input
n = 5
Output
[1,2,3,4,5]
[2,4,6,8,10]
[3,6,9,12,15]
[4,8,12,16,20]
[5,10,15,20,25]
[[1,2,3,4,5],[2,4,6,8,10],[3,6,9,12,15],[4,8,12,16,20],[5,10,15,20,25]]
Twenty-five values, and the last of them is 5 × 5 = 25.

Example 2

Input
n = 3
Output
[1,2,3]
[2,4,6]
[3,6,9]
[[1,2,3],[2,4,6],[3,6,9]]
Three rows of three, and the table reads the same down as across because i × j is j × i.

The Code

function multiplicationTable(n) {
  const rows = [];
  for (let row = 1; row <= n; row++) {
    const line = [];
    for (let col = 1; col <= n; col++) {
      line.push(row * col);
    }
    rows.push(line);
  }
  return rows;
}
multiplicationTable(5);
Done

The first 15 calls, of 37. This one does not fit on a page.

Step through multiplicationTable(5) call by call

Explanation

Both counts run the full range, so neither shapes the result: the grid is square whatever n is. They decide the number in a cell instead — the reverse of the triangles, where the counters chose the positions.

  1. 1

    row is 1 and the inner loop is bounded by n, not by row, so col runs the full 1 to 5. Each line.push(row * col) writes 1 × col, which leaves the row reading as the columns themselves.

    1 2 3 4 5
    0

    row=1col=1 … 5

    rows.push([1, 2, 3, 4, 5])

  2. 2

    row is 2 and col runs 1 to 5 again — the inner bound never moves, which is why this table is square where the triangles are not.

    1 2 3 4 5
    0
    2 4 6 8 10
    1

    row=2col=1 … 5

    rows.push([2, 4, 6, 8, 10])

  3. 3

    row is 3, so row * col gives 3, 6, 9, 12, 15. The two counters decide what is written rather than where it goes, which is the reverse of every triangle above.

    1 2 3 4 5
    0
    2 4 6 8 10
    1
    3 6 9 12 15
    2

    row=3col=1 … 5

    rows.push([3, 6, 9, 12, 15])

  4. 4

    row is 4 — five more products, 4 through 20.

    1 2 3 4 5
    0
    2 4 6 8 10
    1
    3 6 9 12 15
    2
    4 8 12 16 20
    3

    row=4col=1 … 5

    rows.push([4, 8, 12, 16, 20])

  5. 5

    row is 5 and the last row ends on 5 * 5. row++ then fails row <= n, and 25 values across 5 rows are returned.

    1 2 3 4 5
    0
    2 4 6 8 10
    1
    3 6 9 12 15
    2
    4 8 12 16 20
    3
    5 10 15 20 25
    4

    row=5col=1 … 5

    return rows → 5 × 5 values