当前位置:网站首页>PAT_乙级_真题练习_1007_素数对猜想
PAT_乙级_真题练习_1007_素数对猜想
2022-07-31 05:09:00 【xjhdsg】
我的第一篇博客。
这道题刚看完题目时,我第一个想到的是用数组记录所有的素数,再用循环依次比较,但感觉既浪费空间,又浪费时间。
后来又想到斐波那契数列,决定用两个变量,通过在循环过程中,不断地交替值,实时记录结果。
在实现过程中,刚开始,过多的使用if语句,使得逻辑较为混乱,第一次提交检测,竟然直接编译错误,后来理了一下,发现有很多冗余代码,比如,一开始,我给de2赋值,后面还要比较de1和de2的大小,换成de1后,便不需要比较。
在实现的后期,最后一个调试点显示运行超时,换成用sqrt实现判断素数就行了。
#include<stdio.h>
#include<math.h> //调用sqrt函数。
int main(void)
{
int N, count, de1, de2, flag, i, j; //count用来记录结果。
//de1、de2分别用来记录两个相临的较小,较大的素数。
count = de2 = flag = 0;
scanf("%d",&N);
de1 = 3;
for(i = 5; i <= N; i++) //当N < 5时,结果为0。
{
flag = 0;
for(j = 2; j <= sqrt(i); j++) //用sqrt函数来判断素数,可以大幅缩短编译时间。
{
if(i % j == 0)
{
flag++;
}
}
if(flag == 0)
{
de2 = i;
if(de2 - de1 == 2)
{
count++;
}
de1 = de2; //保证交替的完成
de2 = 0;
}
}
printf("%d",count);
return 0;
}边栏推荐
- 目标检测学习笔记
- 三次握手与四次挥手
- tf.keras.utils.pad_sequences()
- C语言实验五 循环结构程序设计(二)
- Distributed Transactions - Introduction to Distributed Transactions, Distributed Transaction Framework Seata (AT Mode, Tcc Mode, Tcc Vs AT), Distributed Transactions - MQ
- Paginate the list collection and display the data on the page
- wx.miniProgram.navigateTo在web-view中跳回小程序并传参
- 数据集划分以及交叉验证法
- Quickly master concurrent programming --- the basics
- 面试Redis 高可靠性|主从模式、哨兵模式、Cluster集群模式
猜你喜欢
随机推荐
Kubernetes 证书可用年限修改
面试官:生成订单30分钟未支付,则自动取消,该怎么实现?
The monitoring of Doris study notes
Mysql——字符串函数
torch.normal函数用法
The TOKEN value of Kubernetes joining the cluster expires
C语言实验四 循环结构程序设计(一)
【一起学Rust】Rust学习前准备——注释和格式化输出
Kubernetes加入集群的TOKEN值过期
C语言实验五 循环结构程序设计(二)
C语言实验三 选择结构程序设计
剑指offer专项突击版 ---- 第2天
C语言指针详解
剑指offer基础版 --- 第22天
如何将项目部署到服务器上(全套教程)
About the problems encountered by Xiaobai installing nodejs (npm WARN config global `--global`, `--local` are deprecated. Use `--location=glob)
Lock wait timeout exceeded解决方案
三次握手与四次挥手
面试Redis 高可靠性|主从模式、哨兵模式、Cluster集群模式
Element concatenation operations in numpy and pytorch: stack, concatenat, cat









