《C++程序设计原理及实践》第四章 习题15

《C++程序设计原理及实践》第四章 习题15
要求:有一个输入值n,输出结果是前n个素数。



#include <iostream>

using namespace std;

int main()
{
    
    
    int n;
    int count = 2;

    cout << "输入需要输出的素数的个数:";
    cin >> n;
    if(n > 2){
    
    
        cout << 2 << endl << 3 << endl;
        int i = 4;
        while (count < n) {
    
    
            bool isPrime = false;                      //判断是否是素数
            for (int j = 2; j < i ; j++) {
    
    
                if(i%j == 0){
    
    
                    isPrime = false;
                    break;
                }
                isPrime = true;
            }
            if(isPrime){
    
                                   //如果是素数,总数加1,并打印出来
                count++;
                cout << i << endl;
            }
            i++;
        }
    }
    else if (n == 1) {
    
    
        cout << 2 << endl;
    }
    else if (n == 2) {
    
    
        cout << 2 << endl << 3 << endl;
    }
    else {
    
    
        cout << "输入不合法!" << endl;
    }

    return 0;
}

猜你喜欢

转载自blog.csdn.net/yongshao8/article/details/108638158