当前位置:   article > 正文

求素数的高效算法_生成素数的高效算法

素数生成算法

素数的高效算法

Prime numbers are natural numbers greater than 1 that have only two divisors (the number itself and 1). By “divisible” we mean dividend % divisor = 0 (% indicates MODULAR. It gives the reminder of a division operation). We’ll follow multiple approaches to find out if a number is prime. Let's find out if P is a prime number.

质数是大于1的自然数,只有两个除数(数字本身和1)。 “可除数”是指股息%除数= 0(%表示模数。它提醒着除法运算)。 我们将采用多种方法来找出数字是否为质数。 让我们找出P是否是质数。

Approach 1: Divide P by all the numbers from 2 to P - 1. If any of these numbers is divided by P then P is not a prime number. The algorithm below returns false if P is divisible by any number between 2 and P - 1. Otherwise, P is a prime number and returns true. 

方法1:将 P除以2到P-1的所有数字。如果这些数字中的任何一个除以P,则P不是质数。 如果P可被2到P-1之间的任意数整除,则下面的算法将返回false,否则,P是质数并返回true。

  1. // This method takes one parameter P
  2. // to check if P is prime
  3. public boolean isPrime(int P) {
  4. for(int i = 2; i < P; ++i) {
  5. if(P % i == 0) return false;
  6. }
  7. return true;
  8. }

Approach 2: Whenever there is a divisor greater than square-root(P), there must be another divisor less than or equal to square-root(P) but NOT greater than square-root(P). For example: Divisors of 20 are: 20 = 1, 2, 4, 5, 10 and 20. For each of these pairs there MUST be least one divisor that is less than or equal to square-root(P).

方法2:每当除数大于平方根(P)时,必须存在另一个除数小于或等于平方根(P)但不大于平方根(P)的除数。 例如:20的除数是:20 = 1、2、4、5、10和20。对于这些对中的每对,必须至少有一个小于或等于平方根(P)的除数。

20 = 1 X 20

20 = 1 X 20

20 = 2 X 10

20 = <

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/你好赵伟/article/detail/75245
推荐阅读
相关标签
  

闽ICP备14008679号