PROBLEM LINK:
Author:Bruno Oliveira
Tester:Shiplu Hawlader and Mahbubul Hasan
Editorialist:Lalit Kundu
DIFFICULTY:
EASY
PREREQUISITES:
Number Theory
PROBLEM:
Find number of 2X2 matrices such that trace=N (N<=2500) and determinant is greater than zero.
EXPLANATION:
Let matrix A=
[ a b ]
[ c d ]
So, a + d = N and a * d > b * c. (From definition of trace and determinant).
We traverse over all possible values of a (ie. from 1 to N-1) to find the solution.
So,
ans=0
for i=1 to N-1:
a=i
d=N-i
ans += number of pairs b,c such that b*c <= (a*d) -1
print ans
So, our problem now is given a P, find number of ordered pairs (since [a1,b1] and [b1,a1] will be counted as different because matrix will be different) A,B such that A * B <= P.
Our solution for above problem can be written as:
sum [over B=1 to P] number of multiples of B less than P+1
The above sum can be written as
summation [B=1 to P] { ⌊ P/B ⌋ }
At this point a very handy fact comes to our rescue.
The sequence ⌊ P/i ⌋ has at most 2 * √P distinct values.
This is because for i > √P, ⌊ P/i ⌋ < √P. Therefore for i = √P + 1 to P, it has only √P distinct values.
The above fact can be used to our advantage. We can sum up the series by summing up, for each distinct value in the sequence, its number of occurrences.
⌊ P/i ⌋ = K
⇒ K ≤ P/i < K+1
⇒ P/(K+1) < i ≤ P/K
⇒ ⌊ P/(K+1) ⌋ < i ≤ ⌊ P/K ⌋
Here is the code to find number of ordered pairs A,B such that A * B <= P.
sum = 0
K = P
imin = 1
while imin ≤ P
imax = ⌊ P/K ⌋
sum += K*(imax - imin + 1)
imin = imax + 1
K = P/imin
print sum
So, overall complexity would be N*√P ie. N*N.
Reference taken from COOLGUYS editorial
AUTHOR'S AND TESTER'S SOLUTIONS:
To be updated soon.