defsieve_of_eratosthenes(n): is_prime = [True] * (n + 1) is_prime[0], is_prime[1] = False, False p = 2 while (p * p <= n): if is_prime[p]: for i inrange(p * p, n + 1, p): is_prime[i] = False p += 1 prime_numbers = [p for p inrange(n + 1) if is_prime[p]] return prime_numbers
# 示例 n = 30 print(f"小于等于 {n} 的质数有: {sieve_of_eratosthenes(n)}")
defsieve_of_euler(n): is_prime = [True] * (n + 1) primes = [] for i inrange(2, n + 1): if is_prime[i]: primes.append(i) for p in primes: if i * p > n: break is_prime[i * p] = False if i % p == 0: break return primes
# 示例 n = 30 print(f"小于等于 {n} 的质数有: {sieve_of_euler(n)}")
std::vector<int> sieve_of_euler(int n){ std::vector<bool> is_prime(n + 1, true); std::vector<int> primes; for (int i = 2; i <= n; ++i) { if (is_prime[i]) { primes.push_back(i); } for (int p : primes) { if (i * p > n) break; is_prime[i * p] = false; if (i % p == 0) break; } } return primes; }
intmain(){ int n = 30; std::vector<int> primes = sieve_of_euler(n); std::cout << "小于等于 " << n << " 的质数有: "; for (int prime : primes) { std::cout << prime << " "; } std::cout << std::endl; return0; }
#include<bits/stdc++.h> usingnamespace std; // 欧拉筛算法函数 std::vector<int> sieve_of_euler(int n){ std::vector<bool> is_prime(n + 1, true); std::vector<int> primes; for (int i = 2; i <= n; ++i) { if (is_prime[i]) { primes.push_back(i); } for (int p : primes) { if (i * p > n) break; is_prime[i * p] = false; if (i % p == 0) break; } } return primes; }
intmain(){ int N = 100000,n; vector<int> primes = sieve_of_euler(N); set<int> primes_set(primes.begin(), primes.end()); scanf("%d", &n); for(int i=1;i<=n;++i){ int a; cin >> a; if (primes_set.find(a)!=primes_set.end()) cout << a << " "; } cout << endl; return0; }