number of solutions of x*y<N

716 Views Asked by At

How many solutions (unique pairs (x,y) ) exist for equation $xy < N$ ?
constraints : $x >1 , y>1 , N<=50000$

I tried following method , but it fails for say N=24 , in which i calculate many pairs like (2,3) , (3,2) twice .

Code :

p=0;
for(j=1;j<=sqrt(N);j++,p++)
{
    if(j*j==N)
        continue; // we want <N

    a=N/j;
    if(j*a==N)
        a--;
        a-=p; // don't add (2,1) as (1,2) was already added
    ans+=2*a-1; //(a,b) and (b,a) but don't calculate (a,a) twice
}

EDIT : By unique i mean (1,1) should not be counted twice .
for 24 pairs are :

(1,1)(1,2)(1,3)........(1,22)(1,23)  
(2,1)(2,2)(2,3)........(2,11)
(3,1)(3,2)(3,3)........(3,7)
(4,1)(4,2)...........(4,5)

I have updated code and added comments

2

There are 2 best solutions below

1
On

Try this:

int count = 0;
for(int x = 2; x <= N / 2; x++)
{
    for(int y = 2; x*y < N; y++)
    {
        count++;
    }
}

This is more efficient as it does not require the square root function.

The final value of the variable 'count' is now the number of unique pairs ($(3,2)$ and $(2,3)$ are different).

2
On

The number of non-ordered pair solutions is $$ \frac12\left(\left\lfloor\sqrt{N-1}\right\rfloor+\sum_{k=1}^{N-1}\left\lfloor\frac {N-1}k\right\rfloor\right) $$ The summation counts all the ordered pairs and divides by $2$. However, this divides the pairs $(k,k)$ by two, and they should not be, so the term with the square root should take care of that.