number-is-prime
问题
如何判断一个数字是否是素数
思路
普通方法:从2..√n,如果n可以被整除, 那么n就不是素数
更高效方法:
We can improve this method further. Observe that all primes greater than 3 are of the form 6k ± 1, where k is any integer greater than 0. This is because all integers can be expressed as (6k + i), where i = −1, 0, 1, 2, 3, or 4. Note that 2 divides (6k + 0), (6k + 2), and (6k + 4) and 3 divides (6k + 3). So, a more efficient method is to test whether n is divisible by 2 or 3, then to check through all numbers of the form 6k +-1. This is 3 times faster than testing all numbers up to √n.
所有整数都可以用6k + i表示,其中i = -1, 0, 1, 2, 3, 4,其中6k + 0, 6k + 2, 6k + 4可以被2整除, 6k + 3 可以被3整除.
所以,素数一定是包含在 6k-1 或者 6k+1里
代码
1 | #include <stdio.h> |
参考链接
https://alexanderell.is/posts/rpc-from-scratch/
https://en.wikipedia.org/wiki/Primality_test