在 C 语言中寻找素数有两种方法:从 2 到根号 n 遍历,检查数字是否能被比它小的数字整除。使用埃拉托斯特尼筛法,标记所有非素数,未标记的数字即为素数。

C 语言中寻找素数的方法
素数是一个只能被 1 和它本身整除的正整数。在 C 语言中,有多种方法可以找出素数。
方法 1:从 2 到根号 n 遍历
最直接的方法是从 2 到数字 n 的平方根遍历。对于每个数字 i,我们检查它是否能被比它小的任何数字整除。如果没有,则它是素数。
#include <stdio.h>
int is_prime(int n) {
if (n <p><strong>方法 2:埃拉托斯特尼筛法</strong></p><div class="aritcle_card flexRow artxards">
<div class="artcardd flexRow">
<a class="aritcle_card_img" rel="nofollow" href="/ai/3653" title="Rephrase.ai"><img
src="https://img.php.cn/upload/ai_manual/001/246/273/178599561646111.png" alt="Rephrase.ai" onerror="this.onerror='';this.src='/static/lhimages/moren/morentu.png'" ></a>
<div class="aritcle_card_info flexColumn">
<a rel="nofollow" href="/ai/3653" title="Rephrase.ai" class="overflowclass">Rephrase.ai</a>
<p class="overflowclass">Rephrase.ai是一款AI文本写作工具,AI文字到视频生成。</p>
</div>
<a rel="nofollow" href="/ai/3653" title="Rephrase.ai" class="aritcle_card_btn flexRow flexcenter"><b></b><span>下载</span>
</a>
</div>
</div>
<p>埃拉托斯特尼筛法是一种更有效的方法,可以找到给定范围内的所有素数。</p>
<p>该算法从一个包含所有数字的数组开始。然后,它从 2 开始,并标记数组中的所有 2 的倍数。然后,它从 3 开始,并标记数组中所有 3 的倍数,但不包括 2 的倍数。此过程一直持续到给定范围内的最高数字。</p>
<p>最后,数组中未被标记的数字是素数。</p>
<pre class="brush:php;toolbar:false;">#include <stdio.h>
#include <stdlib.h>
int main() {
int n;
printf("输入要查找素数的范围上限:");
scanf("%d", &n);
// 创建一个包含所有数字的数组
int *numbers = (int *)malloc(sizeof(int) * (n + 1));
for (int i = 0; i </stdlib.h></stdio.h>
13万字C语言保姆级教程(深入):立即使用
在学习笔记中,你将探索c语言的核心概念和高级技巧!










