寻找质数

// CPP.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"
#include <iostream>
#include <ctime>

using namespace std;

bool IsPrime(const int a){
    bool flag = true;
    int b = a / 2;  // 这里是a除以2,没有必要计算更大的值
    while (b >= 2){
        if (a % b == 0){
            flag = false;
            break;
        }
        else{
            b--;
        }
    }
    return flag;
};

int _tmain(int argc, _TCHAR* argv[])
{
    int a;
    cin >> a;
    clock_t start, end;
    start = clock();
    for (int i = 2; i < a + 1; i++){
        if (IsPrime(i))
            cout << i << " ";
    }
    end = clock();
    cout << "Run time: " << (double)(end - start) / CLOCKS_PER_SEC << "S" << endl;
    return 0;
}
原文地址:https://www.cnblogs.com/shuada/p/3468261.html