当前位置:网站首页>【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;
}
边栏推荐
- File contains vulnerability (I)
- A collection of commonly used plug-ins for idea development tools
- 我所理解的DRM显示框架
- Uva548 tree
- 数据库学习总结5
- Technologists talk about open source: This is not just using love to generate electricity
- PHP gets CPU usage, hard disk usage, and memory usage
- Minimum value ruler method for the length of continuous subsequences whose sum is not less than s
- How vite is compatible with lower version browsers
- PHP array to XML
猜你喜欢

Minimum value ruler method for the length of continuous subsequences whose sum is not less than s

数理统计与机器学习

OLED12864 液晶屏

Matplotlib double Y axis + adjust legend position

Stick to the big screen UI, finereport development diary

Win10 copy files, save files... All need administrator permission, solution

【論文翻譯】GCNet: Non-local Networks Meet Squeeze-Excitation Networks and Beyond

Regular expression summary

软件测试答疑篇

Pytorch Basics
随机推荐
Record sentry's path of stepping on the pit
Several keywords in C language
1036 Boys vs Girls
深度学习分类网络--VGGNet
3D printer G code command: complete list and tutorial
PHP gets CPU usage, hard disk usage, and memory usage
Basic use of form
Matplotlib double Y axis + adjust legend position
Summary of MySQL constraints
如何写出好代码 — 防御式编程指南
Zzuli:1061 sequential output of digits
1035 Password
[whether PHP has soap extensions installed] a common problem for PHP to implement soap proxy: how to handle class' SoapClient 'not found in PHP
With an amount of $50billion, amd completed the acquisition of Xilinx
RNN recurrent neural network
460. LFU cache bidirectional linked list
Common protocols and download paths of NR
正则表达式总结
PHP read file (read the specified line containing a string in the file)
1037 Magic Coupon