簡體   English   中英

我不了解此質數檢查器(Java)背后的邏輯

[英]I do not understand the logic behind this prime number checker (Java)

我不明白這個數字檢查器背后的邏輯,我想知道是否有人可以幫助我更好地理解它。

這是代碼:

我將盡力評論正在發生的事情,但我不完全了解。

//find prime numbers between 2 and 100

class PrimeNumberFinder {
    public static void main(String args[]) {

        int i, j; // declare the integer variables "i" and "j"
        boolean isPrime; // declare the Boolean variable is prime but do not assign value

        // create a for loop that starts at two and stops at 99.
        for (i=2; i < 100 ; i++) {
            isPrime = true; // I do not know why isPrime is set to true here.
            // This is where I get confused badly.. we give the "j" variable a value of two and check to see if it's less than whatever "i" divided by "j" is.             
            // If "i=2" then how would j (which is = 2) be less than or equal to i/j (2/2)? 

            for (j = 2; j <= i/j; j++)
                if ((i%j) == 0) isPrime = false; // If a certain number goes in evenly that isn't 1, or "i" itself, it isn't prime so we set the boolean to false

            if (isPrime) // if true print i
                System.out.println(i + " Is a prime number");


        }
    }
}

如您所見,第二個for循環及其中發生的幾乎所有事情都使我感到困惑,尤其是“ j <= i / j”,因為對我而言j總是會變得更大。為什么“ j”甚至會增加? 您不能僅將其除以2並確定它是否是素數?

非常感謝您的幫助,感謝您的閱讀。

讓我們逐行處理它。

int i, j;
boolean isPrime;

我們首先聲明變量。 沒什么好看的。

for (i=2; i < 100; i++) {
    isPrime = true;

在這里,我們進入循環,該循環基本上包含我們要檢查的所有數字(此處為2-99)。 我們還聲明,當前數字是質數(除非另有證明)。

    for (j = 2; j <= i/j; j++)
        if ((i%j) == 0) isPrime = false;

現在,這里就是魔術發生的地方。 我們將檢查是否可以將當前數i平均除以從j == 2i/j的任何整數( i/j最終只是編寫Math.sqrt(i) )。 那么為什么要一直到那兒呢?

好吧,假設我們有兩個因數ab ,使得a * b = i 現在,如果除數a大於i平方根,則另一個除數b將小於i平方根。 如果不是,則a * b > i ,這是不可能的。

因此,如果我們找到了可以平均除法的情況,則這顯然意味着當前數不是素數,並且將isPrime變量設置為false

    if (isPrime) // if true print i
        System.out.println(i + " Is a prime number");

}

因此,如果我們仍然具有isPrime == true ,則意味着當前數字經受住了我們的測試,我們可以將其打印出來。

兩個進一步的改進;

  1. 一旦知道數字不是素數,就無需檢查任何其他除數,因此我們想退出循環並因此break; 語句可以添加。
  2. 2唯一的偶數質數,因此也可以在j == 3處開始第二個循環,並在每次執行后加2 然后,您將不得不分別考慮i == 2的情況。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM