微软的判断一个数是不是质数的算法

质数大家都知道概念,质数定义为在大于1的自然数中,除了1和它本身以外不再有其他因数。我们最能想到的是进行循环 的除法,下面是微软提供的质数算法。

//判断一个数是不是质数 
public static bool IsPrime(int candidate) {
//num&1 取与运算,可以把奇数偶数 刷选出来,因为偶数不是质数(2除外)
if ((candidate & 1) != 0) { int limit = (int)Math.Sqrt(candidate); //求根号 相当于乘法中的中位数 for (int divisor = 3; divisor <= limit; divisor += 2) //每次+2是跳过 偶数 { if ((candidate % divisor) == 0) return false; } return true; } return (candidate == 2); //最后这个保证2也是质数 }

猜你喜欢

转载自www.cnblogs.com/wwkk/p/10335516.html