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

求素数的高效算法

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 = <

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值