当前位置:网站首页>【C语言】筛选法求素数
【C语言】筛选法求素数
2022-07-02 05:52:00 【SouLinya】
题目
描述
用筛选法求n以内的素数。筛选法求解过程为:将2~n之间的正整数放在数组内存储,将数组中2之后的所有能被2整除的数清0,再将3之后的所有能被3整除的数清0 ,以此类推,直到n为止。数组中不为0 的数即为素数。
输入描述
多组输入,每行输入一个正整数(不大于100)。
输出描述
针对每行输入的整数n,输出两行,第一行,输出n之内(包括n)的素数,用空格分隔
示例
输入:20
输出:
2 3 5 7 11 13 17 19
11
一、思路
常见的求判断素数的方法有试除法,还有就是用sqrt或1/2。筛选法与试除法相似,每个数都要除以除1和它本身之外的数进行判断。筛选法的关键在于:(1)要求将2-n的数字先存入数组中;(2)在将2之后的,注意是2之后的数字能被2整除的清零,然后向后移一位,从3开始,在将3之后的能被3整除的清零,依次类推,直到n。简单说就是最开始指向的是数组的2后3,一轮循环遍历除以2后,数组最开始指向的位置向后偏1,指向数组3后的4,考虑如何平衡循环i和j的值。
二、代码实现
#include<stdio.h>
int main()
{
int n;
int count=0;
int arr[100]={
0};
while(scanf("%d",&n)!=EOF)
{
int j=0;
int i=0;
for(i=2;i<=n;i++)
{
arr[j++]=i;//赋值
//arr[0]=2,arr[1]=3...arr[18]=20
}
//清零
for(i=2;i<=n;i++)//除数的变化
{
for(j=i-1;j<n-1;j++)//被除数的变化
{
//开头的数是+1变化的,所以我们利用i
if(arr[j]%i==0)
{
arr[j]=0;
}
}
}
//打印
//由于会多初始化一个数,所以i<n-1
for(i=0;i<n-1;i++)
{
if(arr[i]!=0)
{
count++;
printf("%d ",arr[i]);
}
}
printf("\n%d\n",n-1-count);
}
return 0;
}
边栏推荐
- vite如何兼容低版本浏览器
- Gcnet: non - local Networks meet Squeeze excitation Networks and Beyond
- Mathematical statistics and machine learning
- 我所理解的DRM显示框架
- php内的addChild()、addAttribute()函数
- Zzuli:1066 character classification statistics
- Here comes a new chapter in the series of data conversion when exporting with easyexcel!
- Software testing learning - day 4
- File contains vulnerability (I)
- PHP read file (read the specified line containing a string in the file)
猜你喜欢

Vscode paste image plugin saves image path settings

vite如何兼容低版本浏览器

With an amount of $50billion, amd completed the acquisition of Xilinx

2022-2-15 learning xiangniuke project - Section 8 check login status

Software testing learning - day 4

软件测试基础篇

mysql的约束总结
![[personal test] copy and paste code between VirtualBox virtual machine and local](/img/ce/eaf0bd9eff6551d450964da72e0b63.jpg)
[personal test] copy and paste code between VirtualBox virtual machine and local

How to write good code - Defensive Programming Guide

深度学习分类网络--Network in Network
随机推荐
Brew install * failed, solution
运动健身的一些心得经验
Basic use of form
深度学习分类网络--VGGNet
1035 Password
RGB 无限立方体(高级版)
软件测试答疑篇
Common protocols and download paths of NR
1035 Password
Record sentry's path of stepping on the pit
DRM display framework as I understand it
正则表达式总结
PHP inner class name is the same as the inner class method name
LCD之MIPI协议的一些说明
js判断移动端还是pc端
Zzuli:1067 faulty odometer
数据库学习总结5
文件包含漏洞(一)
mysql的约束总结
TypeScript的泛型和泛型约束