在 findNextPrime 方法中,为什么我们需要找到 'num'、sqt 的平方根,并在 for 循环中使用它?

Within findNextPrime method, why do we need to find the square root of 'num', sqt, and use it in a for loop?

我正在尝试解决 'finding the next prime number after a given number' 初学者的问题。我在网上看到这段代码,它运行得很好,但我似乎无法理解为什么在 findNextPrime 方法中,我们需要找到 'num'、sqt 的平方根,并在 for 循环中使用它。有人可以向我解释一下数学原理和背后的原因吗?

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

    }
}

OK 求出例如 36 的因式,你得到 1,2,3,4,6,9,12,18,36。

当你知道 2 是一个因数时,你也可以算出 18 是一个因数。对于小于 sqrt(36) 的每个因子,它都会有一个大于 sqrt(36) 的对应因子。因此,通过在中点之后继续,您将只找到您已经找到的因素。

所以如果你知道这个数字在中途点之前没有任何因数,你可以得出它没有因数的结论。