Problem
Given integers N and X, write a function that returns the number of times X appears as a value in an N by N multiplication table.
Suppose you have a multiplication table that is N by N. That is, a 2D array where the value at the i-th row and j-th column is (i + 1) * (j + 1) (if 0-indexed) or i * j (if 1-indexed).
Examples
Example 1:
| |
And all the 12’s are highlighted below:
$$ \begin{bmatrix} 1 & 2 & 3 & 4 & 5 & 6 \\ 2 & 4 & 6 & 8 & 10 & \color{orange} 12 \\ 3 & 6 & 9 & \color{orange} 12 & 15 & 18 \\ 4 & 8 & \color{orange} 12 & 16 & 20 & 24 \\ 5 & 10 & 15 & 20 & 25 & 30 \\ 6 & \color{orange} 12 & 18 & 24 & 30 & 36 \end{bmatrix} $$
Solution
Method 1 -Simple Iteration with division operator
We can iterate from 1 to N for both row (i) and column (j) indices and count each time their product equals X.
We can see that for number x to occur, we need i * j == x. That means x is divisibly by both i and j. x % i == 0 and x % j == 0.
But for eg. x = 12, we can choose i = 6, j = 2, then it is good. x % i == 0 and x % j == 0.
We cannot choose, i = 1, j = 12, even though x % i == 0 and x % j == 0 still holds, but it will not exist in table.
So:
- If
Xis divisible byiand the division result is<= N, then this pair(i, j)is a valid occurrence in the table.
Also, to optimize, you can iterate only one index (either row or column), and for each value i, you can calculate whether a corresponding j exists such that i * j == x.
Code
| |
Complexity
- ⏰ Time complexity:
O(n) - 🧺 Space complexity:
O(1)
Method 2 - Iterate till square root of n
Lets look at the square table again. The idea is that if you have a multiplication of two integers i and j that equals X (where i and j are within the range [1, N]), then one of the integers must be less than or equal to sqrt(X), and the other must be greater than or equal to sqrt(X) and less than or equal to N.
$$
\begin{bmatrix}
1 & 2 & 3 & 4 & 5 & 6 \\
2 & 4 & 6 & 8 & 10 & \color{orange} 12 \\
3 & 6 & 9 & \color{orange} 12 & 15 & 18 \\
4 & 8 & \color{orange} 12 & 16 & 20 & 24 \\
5 & 10 & 15 & 20 & 25 & 30 \\
6 & \color{orange} 12 & 18 & 24 & 30 & 36
\end{bmatrix}
$$
Look at the diagonal elements, they are perfect squares - 1, 4, 9, 16… if that is the case, we should add 1 more to the answer, as this value occurs on diagonal.
Code
| |
Complexity
- ⏰ Time complexity:
O(√x) - 🧺 Space complexity:
O(1)