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;
}
}
}
}