I need to get two factors ( x, y ) of a given number ( n ) such that:
- x * y <= n
- x * y should be as close to n as possible
- x and y should be as close to each other as possible.
Examples:
- n = 16 => x = 4, y = 4
- n = 17 => x = 4, y = 4
- n = 18 => x = 6, y = 3
- n = 20 => x = 5, y = 4
Any language will do but preferably php.
EDIT -- CLARIFICATION
I want to create a rectangle, x units wide * y units tall such that its area is as close to n as possible. x and y must be integers. If n is a prime number then factors of n - 1 are acceptable.
Here is a PHP function that prioritize the two 'factors' being close to each other over having exact factors:
An idea from me (more pseudo then php)
I'd have all the factors written to an array using the following code.
Then I'd loop through the array to check which ones can actually be used. For more on this algorithm, check out http://pyfon.blogspot.com.au/2012/09/list-factors-of-number-in-python.html
Your specifications weren't quite exact enough. You stated that you wanted factors, yet in your test case 4 is not a factor of 17
The following pseudo code works prioritizing that one factor is exact
Where as a simple sqrt statement will work for ensuring that the numbers are as close together as possible, but doesn't guarantee that they are factors.
You need to decide how important your three rules are.
Possibility 1: If x * y being as close to n as possible is true then n=17 => 1,17 not 4,4. In this case you want factorisation and there are lots of ways to do it, but code like this is simple:
Possibility 2: If being close to each other is more important you'd expect n=18=>4,4 rather than 3,6, and this code would work. This however is not factors.
The problem as written is unsolvable without a clearer specification.
EDIT ------------
Now the spec has been edited it is now defined, but you need to do Possibility 1, see if the result is prime (1 is one of the values) and then if it is repeat doing Possibility 2. However, I doubt this is what whichever teacher wrote this as homework intended.