2

I have two numbers N and M. I efficiently want to calculate how many pairs of a,b are there such that 1<=a<=N and 1<=b<=M and a*b is a perfect square.

I know the obvious N*M algorithm to compute this. But i want something better than that. Thanks for any help in advance. A pseudo code will be more helpful.

EDIT : I think it can be done in a better time may O(m+n) or something like that but calculating new pairs directly from previous pairs rather than iterating over all a and b.

Damian Yerrick
  • 4,602
  • 2
  • 26
  • 64
user1465557
  • 329
  • 2
  • 4
  • 11
  • Am I missing something or is the answer not obviously just take the intersection of 1, 2, ..., N and 1, 2, ..., M and then pair each member of the result with itself? – stanekam Nov 29 '14 at 19:40
  • 1
    @iShouldUseAName: `2*8 == 16` – user2357112 Nov 29 '14 at 19:50
  • 1
    @iShouldUseAName A quick counter-example : N=5, M=10. Then (4,9) works because 4*9 = 36 = 6². – Cimbali Nov 29 '14 at 19:50
  • There's **nothing too broad** with this question. It asks for a solution to a concrete problem similar to e.g. project Euler. I can't see any good algorithm, but maybe others can. – maaartinus Apr 27 '15 at 12:11

2 Answers2

3

My approach would be this:

  1. for s is quare and s <= N*M

    1. Do a prime factorization of s.

    2. iterate over the partitions of this prime factorization and check which ones fullfill your requirement

Iterating over the possible partitions may be a bit tricky, but I'm quite certain that this is the most efficient approach that is possible.

Iterating over square numbers, on the other hand, is trivial:

for(int i = 0, square = 0; /*whatever*/; square += 2*i++ + 1)
cmaster - reinstate monica
  • 38,891
  • 9
  • 62
  • 106
0

I would go for a way using prime decompositions. Get a hold of all the prime numbers between 1 and max(N,M), and let us call them the (p0, p1, ... pn)

Then any number a <= N and b <= M can be written as the product of the pi^ai and the product of the pi^bi, for i from 1 to n, where the ai and bi can be any positive integer or 0.

Then, any product a*b can be written as the pi^(ai+bi), and the caracterization of a perfect square in that writing would be that all the (ai+bi) need to be even (0 is even, for the record).

Then you somehow need to iterate over all the (ai) such that a <= N, and for each set of (ai) generate all the (bi) such that b <= M and all the (ai+bi) are even.

Not sure that's the anywhere near efficient, but should work just fine.

Cimbali
  • 11,012
  • 1
  • 39
  • 68