0

When writing an isPrime function to return a Boolean in Java, I have seen a lot of examples where people use Math.sqrt(number) in their for loop. Can someone explain why and what this function is doing in the for loop? I have attached an example for reference. Thanks!

    public boolean isPrime(int n) {
       if (n <= 1) {
           return false;
       }
       for (int i = 2; i < Math.sqrt(n); i++) {
           if (n % i == 0) {
               return false;
           }
       }
       return true;
    }
  • The loop is just checking every possible number which could be divided into a candidate for prime. If a divisor be found, then the number cannot be prime. – Tim Biegeleisen Oct 03 '17 at 02:42
  • 1
    For all cases besides sqrt(n), one of the factors is larger than the other. More particularly, one factor is greater than sqrt(n) and the other is less (otherwise their product couldn't be n). So if you've iterated up to sqrt(n), you have checked one of the factors of every possible pair. – Mad Physicist Oct 03 '17 at 02:50
  • It's also really good for performance if you re-calculate the same square root in every single iteration of the loop. – Dawood ibn Kareem Oct 03 '17 at 03:25
  • 1
    Also, that method, as written, tells me that 9 is prime. – Dawood ibn Kareem Oct 03 '17 at 03:40
  • This is an older question but I think it merits pointing out that this method does not work as written. We must go up to and including the sqrt of a number n. Otherwise we get back false positives like 9 and 25. So the for loop should run until i <= Math.sqrt(n). – Boris Jan 24 '22 at 03:10

2 Answers2

1

If a number is not a prime, it can be factored into two factors f1 and f2

If f1 and f2 are > the sqrt of the number, f1*f2 would be > the number. So at least one of those factors must be <= to the sqrt of the number. To see if a number is actually prime, we only need to test factors that are <= to the sqrt.

user2023608
  • 470
  • 5
  • 18
0

How do you know if a number n is a prime? The first strategy would be to test all numbers, from 2 to (n-1). For every value i, check if n divides by i. If you find such a i, then n is not a prime.

But do you really need to test all values? No, as soon as you have reached the square root of n, you would be testing the same "pair" of values. In other words, sqrt is there to limit the number of tests to be done, hence to improve the performance.

Olivier Liechti
  • 3,138
  • 2
  • 19
  • 26