Skip to content

Instantly share code, notes, and snippets.

@faresbakhit
Created November 18, 2024 20:02
Show Gist options
  • Save faresbakhit/8ced3f3aeaeb436a3398c5db56e335d7 to your computer and use it in GitHub Desktop.
Save faresbakhit/8ced3f3aeaeb436a3398c5db56e335d7 to your computer and use it in GitHub Desktop.
C++ Structured VS. Functional Programming
#include <iostream>
#include <ranges>
#include <cmath>
int main() {
int p, q;
std::cin >> p;
std::cin >> q;
for (const auto &r :
std::views::iota(p, q)
| std::views::filter([](int n) {
return (n > 1) && (n == 2 || (n % 2 && std::ranges::empty(
std::views::iota(2, static_cast<int>(std::sqrt(n)) + 1)
| std::views::filter([n](int i) { return n % i == 0; })))); }))
std::cout << r << ' ';
std::cout << std::endl;
}
#include <iostream>
#include <cmath>
bool isPrime(int n) {
if (n < 2) return false;
if (n == 2) return true;
if (n % 2 == 0) return false;
for (int i = 2; i <= std::sqrt(n); i++) {
if (n % i == 0) return false;
}
return true;
}
void printPrimesInRange(int p, int q) {
for (int n = p; n < q; ++n) {
if (isPrime(n)) {
std::cout << n << ' ';
}
}
std::cout << std::endl;
}
int main() {
int p, q;
std::cin >> p;
std::cin >> q;
printPrimesInRange(p, q);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment