求素数的高效算法
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。
// This method takes one parameter P
// to check if P is prime
public boolean isPrime(int P) {
for(int i = 2; i < P; ++i) {
if(P % i == 0) return false;
}
return true;
}
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 = <