C++关于素数的问题

标签 c++ primes

我正在尝试编写一个程序来确定该数字是质数还是合数。到目前为止我已经做到了。你能给我一些想法让它发挥作用吗?然而,所有素数都会,因为复合数的值既 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_numberhttp://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/

相关文章:

c++ - 用 Armadillo C++ 加载稀疏矩阵

c++ - 跳过第 3 方库中的 #define

C - 打印素数列表(递归)

algorithm - 计算序列中的互素数

c++ - OpenGl - 纹理 glutSolidSphere?

c++ - 试图从函数返回 std::ifstream

java - BigIntegers 的 BigIntegers 的力量

python - 解释这个素数生成器函数,我无法理解[python]

python - python中的随机素数

c++ - 在 C++ 中对特定 header 使用 extern C 关键字是否允许从 void* 转换为 char*?