Let i \cdot j~(i \le j) represent the dimensions of a rectangle that can be formed using the squares. Given that i \le j and i \cdot j \le n, it follows that i ≤ \sqrt{n}.
Let's iterate over the smaller side of the rectangle from to \sqrt{n}. For each , iterate over the second side , from until i \cdot j \le n. In the variable , count the number of such pairs .
cnt = 0;
for (i = 1; i <= sqrt(n); i++)
for (j = i; i * j <= n; j++)
cnt++;The second loop can be replaced with a formula. Notice that in the loop runs from to . Therefore, during the -th iteration, the value of increases by n / i - i + 1. The double loop can thus be rewritten as follows:
cnt = 0;
for (i = 1; i <= sqrt(n); i++)
cnt = cnt + (n / i - i + 1);Example
Consider the first test case where n = 6. The smaller side of the rectangle iterates from to \lfloor\sqrt{6}\rfloor = 2.
For i = 1, the second side can take values from i = 1 to n / i = 6. This gives us rectangles:
For i = 2, the second side can take values from i = 2 to n / i = 3. This gives us rectangles:
In total, for n = 6, there are possible rectangles.
Algorithm realization
Read the input value of .
scanf("%d", &n);Compute the answer.
cnt = 0;
for (i = 1; i <= sqrt(n); i++)
cnt = cnt + (n / i – i + 1);Print the answer.
printf("%lld\n", cnt);Python realization
import mathRead the input value of .
n = int(input())Compute the answer.
cnt = 0
for i in range(1, int(math.sqrt(n)) + 1):
cnt += (n // i - i + 1)Print the answer.
print(cnt)