C++ 求质数

2021-08-29  本文已影响0人  奇点创客

生成前 n 个素数,n 由用户提供,并保存到文件

#include <iostream>
#include <ranges>
#include <cmath>
#include <cstdlib>
#include <fstream>
#include <chrono>

class ElapesdTime {
public:
    ElapesdTime() {
        start_ = std::chrono::steady_clock::now();
    }
    ~ElapesdTime() {
        auto end_ = std::chrono::steady_clock::now();
        auto elapsed_time = std::chrono::duration<double>(end_ - start_);
        std::cout << "Elapsed time: " << elapsed_time.count() << " s\n";
    }
private:
    std::chrono::steady_clock::time_point start_;
};

bool is_prime(uint64_t n)
{
    if (n == 0 or n == 1) return false;
    if (n == 2 or n == 3) return true;
    if (n % 6 != 1 and n % 6 != 5) return false;

    auto n_sqrt = static_cast<uint64_t>(std::sqrt(n));
    for (uint64_t i = 5; i <= n_sqrt; i += 6) {
        if (n % i == 0 or n % (i + 2) == 0)
            return false;
    }
    return true;
}
int main(int argc, char* argv[])
{
    ElapesdTime et;
    uint64_t prime_amount{ 100'0000ull };  // 欲获取的质数个数
    if (argc == 2) prime_amount = std::atoi(argv[1]);

    auto primes_view = [](uint64_t n) {
        using namespace std::views;
        return iota(2) | filter(is_prime) | take(n);
    };

    std::ofstream fout{ "primers.txt" };
    for (auto prime : primes_view(prime_amount)) 
        fout << prime << '\n';

    std::cout << "Finish! " << std::endl;
}
上一篇 下一篇

猜你喜欢

热点阅读