0

I'm trying to solve the beginner's problem of 'finding the next prime number after a given number'. I saw this code online and it works perfectly, but I can't seem to understand why, within findNextPrime method, we need to find the square root of 'num', sqt, and use it in a for loop. Could someone please explain to me the mathematics and reasons behind it?

import java.util.Scanner;

public class NextPrime {

    public static void main(String[] args) {
        System.out.println("Enter the number to find the next prime to it.");
        Scanner sc = new Scanner(System.in);
        int i1 = sc.nextInt();
        sc.close();

        System.out.println("the next prime number to " + i1 + " is " + findNextPrime(i1));
    }

    public static int findNextPrime(int num) {
        while (true) {
            boolean isPrime = true;
            num += 1;
            int sqt = (int) Math.sqrt(num);
            for (int i = 2; i <= sqt; i++) {
                if (num % i == 0) {
                    isPrime = false;
                    break;
                }
            }
            if (isPrime) {
                return num;
            }
        }

    }
}
halfer
  • 19,824
  • 17
  • 99
  • 186
Thor
  • 9,638
  • 15
  • 62
  • 137
  • 1
    If a number `n` is not divisible by any number less than `sqrt(n)` that it cannot be divisible by any number greater than `sqrt(n)`. if `n == p * q` then either `p` or `q` have to be less than `sqrt(n)` – Miserable Variable Jan 20 '16 at 01:52

1 Answers1

3

OK find the factors of for example 36, You get 1,2,3,4,6,9,12,18,36.

When you know 2 is a factor you can also figure out 18 is a factor. For every factor smaller then sqrt(36) it will have a corresponding factor larger then sqrt(36). So by continuing after the halfway point you will just find the factors you have already found.

So if you know that the number does not have any factors until the halfway point, you can conclude that it has no factors.

the pickle
  • 668
  • 8
  • 18