Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to find divisor of a number that is closest to its square root?

I’ve been trying to make a program that gives me a divisor of a number n that is closest to its square root.

I’ve tried to accomplish this by using this program:

public static int closestDivisor(int n) {
    for (int i = n/ 2; i >= 2; i--) {
        if (n % i == 0) {
            return i;
        }
    }
    return 1;
}

However, when I run this:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

System.out.println(closestDivisor(42));

I get 21 when expecting either 6 or 7 because those are the closest divisors of 42.

>Solution :

if (i < 4) return 1;

int divisor = 1;
for (int i = 2; i < n; i++) {
    if (i * i == n) return i;
    if (i * i < n && n % i == 0) divisor = i;
    if (i * i > n) return divisor;
}

return -1; // never executed, unreachable

This code should return the largest number which evenly divides n and which is less than or equal to the square root of n.

You can then look at this number, let’s call it answer, and n/answer, and one of those is guaranteed to be the factor of n closest to the square root of n. To see which is which, we can compare n – answer*answer and (n/answer * n/answer) – n, and see which is smaller; if the first difference is smaller then answer is closer to n, otherwise n/answer is closer to n.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading