algorithm - Understanding the code for finding the permutation of numbers x and y,(less than n) such that x*y is a perfect square and y -x is maximum (x < y) -
i read function in programming blog aforementioned task,but i'm unable understand . (also x*y should maximum).also preference maximizing x*y more y-x .
long long ans = 0; int x,y; for( = 2;i <= n / i;++i){ int k = n / (i * i); int y = k *i*i; int x = k * (i - 1) * (i - 1); if((long long)x * y > ans){ ans = (long long)x * y; x = x; y = y; } }
i <= n / i
ensures valuesx
,y
lessn
, derived square ofi
, inside loop.
(k
derivedn
,i
. ,x
,y
in turn derivedk
,i
.)int k = n / (i * i);
,int y = k * * i;
,int x = k * (i - 1) * (i - 1);
ensures valuex * y
perfect square.
(sincex * y
=k * k * * * (i - 1) * (i - 1)
. i.ex * y
perfect square ofk * * (i - 1)
).
also,x
lessy
becausex
derives(i - 1)
whereasy
i
.- the 3 statements in
if
loop @ end keep track of pair having largestx * y
.
Comments
Post a Comment