素数检查 C++ 函数输出非素数的数字

prime checking c++ function outputs numbers that aren't prime

本文关键字:数字 函数 检查 C++ 输出      更新时间:2023-10-16

我正在制作一个C++程序,它允许您输入一个数字并检查它是否为素数。但它说,像9、15和21这样的数字是素数。我能帮忙吗?这很令人困惑。这是我的函数,检查它是否是素数:

bool isPrime(int num) {
int w = 2;
while (w <= num) {
if (w % num == 0) {
return false;
}
else if (w < num){
w = w + 1;
}
if (w == num) {
w = 0;
return true; 
}
}
}

当你意识到所有大于3的素数都可以写为6n+16n+5,对于自然n时,可以获得Aconcagua的额外加速解。或者更进一步,所有大于5的素数都可以写成30n+m,其中m{1,7,11,13,17,19,23,29}。这就是所谓的车轮分解。

这可以简单地理解为:

  • 2的轮因子分解(cfr.Aconcagua(:如果n不能被2整除,那么n就不能被2的任何倍数整除
  • 6=2x3的轮因子分解:如果n不可被2整除,则n不能被2的任何倍数整除,如果n不能被3整除,那么n-也不能被3的任何倍数所整除
  • 30=2x3x5的车轮因数分解:见上文

因此实现6的Wheel因子分解,快速给出:

if (num == 1)     return false;
if (num  < 4)     return true;
if (num % 2 == 0) return false;
if (num % 3 == 0) return false;
int w = 5;
while (w*w <= num)
{
if(num % (w-2) == 0) return false;
if(num % w     == 0) return false;
w += 6;
}
return true;

该算法的运行速度应为Aconcagua求解速度的2/3。

备注:30的轮分解只会产生较小的加速,因为它只消除了序列30n+25,该序列也被6的轮分解覆盖为6*(5*n+4(+1

备注:这仍然测试不应该测试的数字,例如(w=25而我们已经知道w-2=5被测试,35,49同上,…(

如果你想变得更健壮一点并使用一点内存,你可能会对Eratosthenes筛感兴趣。

其他有用的信息可以在这里找到:primes

已经发现了实际的错误(w % num而不是num % w(,只需要一些额外的提示:

你的代码太复杂了!

while (w <= num)  // why <=? w == num is irrelevant, in worst
// case, it will lead to false negatives (num % num == 0)!
{
if (num % w == 0) // (already fixed!)
{
return false;
}
else if (w < num)
{
w = w + 1;
}
if (w == num) // as you increment by 1, this will always be false unless
// previous test failed - so simply use else instead
{
w = 0;
return true; 
}
}

第一步:

while (w < num)
{
if (w % num == 0)
{
return false;
}
/*else*/ if (w < num) // however, this check is repeated in the while
// loop anyway; no need to do the work twice 
{
++w; // shorter...
}
else
{
// w = 0; // obsolete, we will be destroyed afterwards anyway...
return true; 
}
}

第二步:

while (w < num)
{
if (w % num == 0)
{
return false;
}
++w; // at some point, will reach w == num and the loop won't be re-entered
}
// we did not leave the loop prematurely (-> non-prime), so we are prime:
return true;

优化:

  1. 如果num == n * mn大于sqrt(num),则m较小!因此,当检查m时,n已经被捕获,所以您不必检查大于平方根的值。这将排除大量的数字
  2. 如果n不设计num,那么k * m也不会。对于2的倍数,不从中获利太简单了(尽管仍然很容易,但考虑到3、5…的倍数,它会变得更复杂(

应用这些:

if(num % 2 == 0)
return false;
int w = 3;
while (w*w <= num)  // be aware that I had an error here in my comment
// to the question - cannot fix it any more, though...
{
if(num % w == 0)
return false;
w += 2;
}
return true;

我相信你想要if(num % w == 0)if(w % num == 0)

这里的代码可能有助于`bool isPrime(int num(

int w = 2;
while (w <= num) {
if (num % w == 0) {
return false;
}
else if (w < num){
w = w + 1;
}
if (w == num) {
w = 0;
return true; 
}
}

`

相关文章: