从 main 开始,我试图在 mymath.cpp 中调用一个素数函数——它有一些我不理解的非常奇怪的行为。(注意,该算法还不能工作——但这对我来说并不奇怪。)
奇怪的是,如果我注释掉这一行:
cout << "n:" << lastPrime->pnum <<"\n";
... 在 mymath.cpp 中,我在 main 中的循环只运行了两次。如果我把它留在里面,我在 main 中的循环一直运行到 i = 50;
主程序
#include <iostream>
#include <stdlib.h>
#include <time.h>
#include "stat.h"
#include "mymath.h";
using namespace std;
int main()
{
for (int i = 3; i<= 50; i++)
{
if (isPrime(i))
{
cout << i << " is prime!\n";
}
else
{
cout << i << " is NOT prime\n";
}
}
return 0;
}
MYMATH.CPP
#include "mymath.h"
#include <math.h>
#include <iostream>
using namespace std;
prime two;
prime * lastPrime = &two;
prime * firstPrime = &two;
bool isPrime(long long n)
{
two.pnum=2;
prime * currentPrime = &two;
if ( n < 2)
return false;
long long squareRoot = sqrt(n);
while(true)
{
if (n % currentPrime->pnum==0)
{
//n is divisible by a prime number, nothing left to do.
return false;
}
else
{
//n is not divisible by a prime... check next one
{
if (currentPrime->pprime == 0 || currentPrime->pnum > squareRoot)
{
//this is prime
prime addPrime;
addPrime.pnum=n;
addPrime.pprime=0;
lastPrime->pprime=&addPrime;
lastPrime=&addPrime;
cout << "n:" << lastPrime->pnum <<"\n";
return true;
}
else
{
//may not be prime, check next
currentPrime = currentPrime->pprime;
}
}
}
}
return true;
}