http://www.perlmonks.org?node_id=432598


in reply to Re: OT: Finding Factor Closest To Square Root
in thread OT: Finding Factor Closest To Square Root

You have the right of it. More precisely, take the logarithim. Then the problem becomes finding a sum of log prime factors that is closest to log(N)/2. This problem is reducible to the subset sum problem, which is NP-hard.

Although exact solutions are exponential, heuristics can sometimes generate good answers with minimal effort. One example of a heuristic that might work well is the greedy heuristic. To fill a box of size log(N)/2, put the largest factor into the box. Then put the next largest factor that still fits in the box and insert it. Keep doing this until no more factors fit.

The above will get you the largest factor <= sqrt(N). To get the smallest factor >= sqrt(N), put all the factors in a box, and take them out again largest to smallest, until no more can be taken out. Finally, comapre the two answers to find the closest.

Update: fixed a typo.

-Mark

  • Comment on Re^2: OT: Finding Factor Closest To Square Root

Replies are listed 'Best First'.
Re^3: OT: Finding Factor Closest To Square Root
by QM (Parson) on Feb 20, 2005 at 05:33 UTC
    To fill a box of size log(N)/2, put the largest factor into the box. Then put the next largest factor that still fits in the box and insert it. Keep doing this until no more factors fit.

    The above will get you the largest factor <= sqrt(N). To get the smallest factor >= sqrt(N), put all the factors in a box, and take them out again largest to smallest, until no more can be taken out. Finally, comapre the two answers to find the closest.

    I don't think that does what you think. For example, 2**3 * 19**3 = 54872, and the square root is 234.277....

    Your method gives 19 as the largest less than the square root, and 2**3 * 19**2 = 2888 as the smallest greater than the square root. Notice that 19*2888 = 54872.

    A better result is 2**3 * 19 = 152 (because 19**2 = 361).

    -QM
    --
    Quantum Mechanics: The dreams stuff is made of

      I think the method I sketched does not do what you think :-)

      Lets take your example. The square root is 234.277. The largest prime factor is 19. The largest remaining factor is 19, but 19*19 > 234.77, so we try the next largest factor, which is 2. 19*2 <= 234.77, so we keep it. The next largest is 2, and 19*2*2 <= 234.77, so we keep it. The next largest (and final) factor is 2, and 19*2*2*2 = 152 < 234.77, so we stop there. 152 is our best attempt for factor closest to but <= sqrt(54872).

      A little thought shows that the greedy method from above will give 54872/152 = 361. If one uses a linear distance, then 152 is the closest factor by the grredy heuristic.

      -Mark