我正在尝试编写一个程序来确定该数字是质数还是合数。到目前为止我已经做到了。你能给我一些想法让它发挥作用吗?然而,所有素数都会,因为复合数的值既 r>0 又 r==0,所以它们将始终被分类为素数。我该如何解决这个问题?
int main()
{
int pNumber, limit, x, r;
limit = 2;
x = 2;
cout << "Please enter any positive integer: " ;
cin >> pNumber;
if (pNumber < 0)
{
cout << "Invalid. Negative Number. " << endl;
return 0;
}
else if (pNumber == 0)
{
cout << "Invalid. Zero has an infinite number of divisors, and therefore neither composite nor prime." << endl;
return 0;
}
else if (pNumber == 1)
{
cout << "Valid. However, one is neither prime nor composite" << endl;
return 0;
}
else
{
while (limit < pNumber)
{
r = pNumber % x;
x++;
limit++;
if (r > 0)
cout << "Your number is prime" << endl;
else
{
cout << "Your number is composite" << endl;
return 0;
}
}
}
return 0;
}
最佳答案
查看http://en.wikipedia.org/wiki/Prime_number和 http://en.wikipedia.org/wiki/Primality_test
The simplest primality test is as follows: Given an input number n, check whether any integer m from 2 to n − 1 divides n. If n is divisible by any m then n is composite, otherwise it is prime.
关于C++关于素数的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2399062/