-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathcpp-range3.cpp
More file actions
38 lines (34 loc) · 925 Bytes
/
cpp-range3.cpp
File metadata and controls
38 lines (34 loc) · 925 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
// cpp-range3.cpp : sum of the first million primes
// note: compile with -std=c++23 or /std:c++latest
#include <ranges>
#include <numeric>
#include <vector>
#include <iostream>
using namespace std::ranges;
int main() {
auto is_prime = [](auto n){
if (n < 2) {
return false;
}
else if (n < 4) {
return true;
}
else if (n % 2 == 0) {
return false;
}
else for (int p = 3; p != n; p += 2) {
if (n % p == 0) {
return false;
}
if (p * p > n) {
break;
}
}
return true;
};
auto pipeline = views::iota(2)
| views::filter(is_prime)
| views::take(1'000'000)
| to<std::vector>();
std::cout << "Sum of the first million primes is: " << std::accumulate(pipeline.begin(), pipeline.end(), 0ULL) << '\n';
}