Find the closest pair of integers (a,b) that make a known product P

127 Views Asked by At

For any positive integer P, is there a formula or an algorithm that can find the closest pair X of integers a and b, that multiplied together result in that integer P?

In other words: knowing P, find closest a and b that satisfy a * b = P

By closest I mean - the difference between a and b is smallest possible.


Square example: I have a number 256. I know, using square root, that a = 16 and b = 16 will be that pair X I'm looking for. For P being a square of any integer this is easy. How about for other integers?

Non-square example: if P = 198, I found that a = 11 and b = 18 is my pair X. This time however I had to go through trial and error (picking random numbers) to find my answer.

  • Is there any way I could calculate the pair X automatically?
  • Is there a name for the problem I'm describing?
  • Am I missing something (such as edge cases that can't be calculated)?

Context (feel free to ignore this): I'm working with images. Sometimes, the data is provided in a flattened format (as one row of numbers), and I'm trying to figure out how to unravel the data back to the image format of width x height (however please don't worry about whether I guess the correct dimensions of the original data - it's irrelevant). Therefore, having a and b closest to each other is needed in my use case.