求出n以内的所有素数

素数筛选法

蓝桥杯经典模板里面提到了这个方法
https://blog.csdn.net/weixin_41793113/article/details/88762953
如下图
在这里插入图片描述

然后
https://blog.csdn.net/liukehua123/article/details/5482854
这篇文章比较详细的讲了筛选法方法,博主有个别错误可以原谅
对于这上面提到的一个问题,就是创建比变量大的数,要用到动态内存我看了下面这篇
http://c.biancheng.net/view/223.html
这篇写的非常详细
具体方法就是

int* const a = (int*)malloc(sizeof(int)*(n+1));
//a就可以看成数组名了,但是这种方法好像没办法把数组所有值赋0 

等下我好像找到方法了

#include<stdio.h>
#include<math.h>
#include<stdlib.h>
#include <string.h>

int main()
{
	int n;
	scanf("%d",&n); 
	int* const a = (int*)malloc(sizeof(int)*(n+1)); 
	memset(a, 0, sizeof(int)*(n+1));
}

然后我写的素数筛选法如下(刚刚开始打竞赛代码比较烂)

//素数筛选法 
#include<stdio.h>
#include<math.h>    //sqrt函数开方 
#include<stdlib.h>  //malloc内存分配 
#include <string.h>  //memset内存初始 
int n;
void judge(int n)
{
	int* const a = (int*)malloc(sizeof(int)*(n+1)); 
	memset(a, 0, sizeof(int)*(n+1));
	*(a+1)=1;//1不是素数 
	for(int i=2;i<sqrt(n);i++)
		if(*(a+i)==0) 
			for(int j=2*i;j<n+1;j=j+i)
				*(a+j)=1;
				
	for(int i=2;i<n+1;i++)	
		if(*(a+i)==0)
			printf("%d  ",i);					
}
int main()
{
	scanf("%d",&n); 
	judge(n);
	return 0;
}

然后(这是再没找到方法之前)
https://blog.csdn.net/Frost_Bite/article/details/88878063
讲了数理知识简化时间复杂度,有很多方法
然而我只看了最简单的如下图
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值