有一个简单的算法,可以判断X是素数,而不要混淆一个凡人的程序员?素数、凡人、程序员、算法

2023-09-10 22:47:12 作者:滥情空心。

我一直在努力工作,通过项目欧拉我的方式,并已经注意到少数的问题问你确定一个素数作为它的一部分。

I have been trying to work my way through Project Euler, and have noticed a handful of problems ask for you to determine a prime number as part of it.

1)我知道我可以通过只分×2,3,4,5,...,X的平方根,如果我得到的平方根,我可以(安全)假设数是素。不幸的是这个解决方案似乎相当klunky。

1) I know I can just divide x by 2, 3, 4, 5, ..., square root of X and if I get to the square root, I can (safely) assume that the number is prime. Unfortunately this solution seems quite klunky.

2)我已经研究过更好的算法如何确定一个数是否为素数,但感到困惑快。

2) I've looked into better algorithms on how to determine if a number is prime, but get confused fast.

有一个简单的算法,可以判断X是素数,而不要混淆一个凡人的程序员?

Is there a simple algorithm that can determine if X is prime, and not confuse a mere mortal programmer?

谢谢了!

推荐答案

第一种算法是相当不错的,并使用了大量的项目欧拉。如果你知道你想你也可以研究埃拉托色尼的筛子的最大数量。

The first algorithm is quite good and used a lot on Project Euler. If you know the maximum number that you want you can also research Eratosthenes's sieve.

如果您保持质数的列表中,您还可以细化第一算法中,只用素数划分,直到数的平方根。

If you maintain the list of primes you can also refine the first algo to divide only with primes until the square root of the number.

使用这两个algoritms(分割和筛)你应该能够解决的问题。

With these two algoritms (dividing and the sieve) you should be able to solve the problems.

修改:如有些评论指出固定名称

Edit: fixed name as noted in comments

 
精彩推荐
图片推荐