簡體   English   中英

不理解代碼來測試數字是否為素數

[英]Do not understand code to test if a number is prime or not

我在網上找到了這個代碼。 這不是我自己的。 這是一個測試給定數字是否為素數的函數。 該代碼用於確定數字是否為素數。 我只是不明白它是如何工作的。

function test_prime(n)  
{  

  if (n===1)  
  {  
    return false;  
  }  
  else if(n === 2)  
  {  
    return true;  
  }else  
  {  
    for(var x = 2; x < n; x++)  
    {  
      if(n % x === 0)  
      {  
        return false;  
      }  
    }  
    return true;    
  }  
}  

alert(test_prime(25)); 

第一個if和else if語句對我有意義。 如果n等於1,則返回false,即1不是素數。 否則,如果n等於2,則返回true,因為2是素數。

else語句中的所有內容對我來說都沒有意義。 如果你調用函數測試25,這不是素數,25%x,x = 2,等於1.那么為什么函數會返回false?

我知道有一些關於for循環我不理解。

如果n既不是1也不是2,則取2和n之間的數字范圍,並檢查n是否可被任何這些數字整除。 如果是,那么它不是素數,所以你返回false。 如果范圍中沒有數字除以n ,那么n必須是素數。

else塊的解釋

else  
  {  
    for(var x = 2; x < n; x++)  // Iterating over possible divisors i.e number - 1
    {  
      if(n % x === 0) // Checking whether the number is divisible by any number, if it is then return false i.e. number is not a prime number  
      {  
        return false;  
      }  
    }  
    // If the number is not divisible by any number return true
    return true;    
  }  
   for(var x = 2; x < n; x++)  
    {  
      if(n % x === 0)  
      {  
        return false;  
      }  

}

我想你會看到這個: https//docs.oracle.com/javase/tutorial/java/nutsandbolts/for.html

x的值介於2和n-1之間。 當你處於循環中時,x的值正在改變:首先x = 1,然后x = 2,后來x = 3 ......當x = 5時,條件為真,然后返回false。

暫無
暫無

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

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