求解100以内的素数是一个常见的编程任务。素数是大于1且只能被1和自身整除的整数。我们将使用三种常见的方法来解决这个问题:穷举法、埃拉托斯特尼筛法和优化的埃拉托斯特尼筛法。
#include
#include
bool is_prime(int num) {
if (num < 2)
return false;
for (int i = 2; i < num; i++) {
if (num % i == 0)
return false;
}
return true;
}
void print_primes(int limit) {
for (int i = 2; i <= limit; i++) {
if (is_prime(i))
printf("%d ", i);
}
}
int main() {
int limit = 100;
printf("Prime numbers up to %d:\n", limit);
print_primes(limit);
return 0;
}
#include
#include
void sieve_of_eratosthenes(int limit) {
bool is_prime[limit + 1];
for (int i = 0; i <= limit; i++)
is_prime[i] = true;
for (int p = 2; p * p <= limit; p++) {
if (is_prime[p]) {
for (int i = p * p; i <= limit; i += p)
is_prime[i] = false;
}
}
printf("Prime numbers up to %d:\n", limit);
for (int i = 2; i <= limit; i++) {
if (is_prime[i])
printf("%d ", i);
}
}
int main() {
int limit = 100;
sieve_of_eratosthenes(limit);
return 0;
}
#include
#include
void optimized_sieve_of_eratosthenes(int limit) {
bool is_prime[limit + 1];
for (int i = 0; i <= limit; i++)
is_prime[i] = true;
for (int p = 2; p * p <= limit; p++) {
if (is_prime[p]) {
for (int i = p * p; i <= limit; i += p)
is_prime[i] = false;
}
}
printf("Prime numbers up to %d:\n", limit);
for (int i = 2; i <= limit; i++) {
if (is_prime[i])
printf("%d ", i);
}
}
int main() {
int limit = 100;
optimized_sieve_of_eratosthenes(limit);
return 0;
}