Last active
October 12, 2020 02:50
-
-
Save razimantv/84d6e0e471ec67e7224e4ba7601e67e1 to your computer and use it in GitHub Desktop.
Comparing prime generation the old way and the C++20 way
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <chrono> | |
#include <iostream> | |
#include <numeric> | |
#include <ranges> | |
#include <vector> | |
const int N = 10000000; | |
int main() { | |
auto t1 = std::chrono::steady_clock::now(); | |
auto isprime_old = [](int n) { | |
if (n < 2) return false; | |
for (int i = 2; i * i <= n; ++i) { | |
if (n % i == 0) return false; | |
} | |
return true; | |
}; | |
long long psum = 0; | |
for (int i = 1; i < N; ++i) { | |
if (isprime_old(i)) psum += i; | |
} | |
std::cout << psum << std::endl; | |
auto t2 = std::chrono::steady_clock::now(); | |
std::chrono::duration<double> dt1 = t2 - t1; | |
std::cout << dt1.count() << " seconds" << std::endl; | |
auto isprime_new = [](int n) { | |
using namespace std::views; | |
return n > 1 and ( | |
iota(2) | | |
take_while([n](int k) { return k * k <= n; }) | | |
filter([n](int k) { return n % k == 0; }) | |
).empty(); | |
}; | |
auto primes = std::views::iota(1, N) | std::views::filter(isprime_new); | |
std::cout << std::accumulate(primes.begin(), primes.end(), 0ll) << std::endl; | |
auto t3 = std::chrono::steady_clock::now(); | |
std::chrono::duration<double> dt2 = t3 - t2; | |
std::cout << dt2.count() << " seconds" << std::endl; | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment