当前位置:网站首页>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;
}
边栏推荐
猜你喜欢
账号或密码多次输入错误,进行账号封禁
分布式事务——分布式事务简介、分布式事务框架 Seata(AT模式、Tcc模式、Tcc Vs AT)、分布式事务—MQ
“档次法”——用于物品体积分布不均匀的01背包问题的求解方法
Interviewer, don't ask me to shake hands three times and wave four times again
分布式事务处理方案大 PK!
The monitoring of Doris study notes
The interviewer asked me TCP three handshake and four wave, I really
Swordsman Offer Special Assault Edition ---- Day 6
C语言实验一 熟悉C程序的环境
剑指offer专项突击版 ---- 第1天
随机推荐
“档次法”——用于物品体积分布不均匀的01背包问题的求解方法
tf.keras.utils.get_file()
目标检测学习笔记
[MQ I can speak for an hour]
数据库上机实验4 数据更新和视图
Interview Redis High Reliability | Master-Slave Mode, Sentinel Mode, Cluster Cluster Mode
剑指offer基础版 ----- 第28天
The monitoring of Doris study notes
C语言实验五 循环结构程序设计(二)
数据库上机实验3 连接查询和分组查询
Unity Framework Design Series: How Unity Designs Network Frameworks
关于LocalDateTime的全局返回时间带“T“的时间格式处理
Flink sink redis 写入Redis
梳理一下自己常用的快捷键
Centos7 install mysql5.7
a different object with the same identifier value was already associated with the session
Kubernetes加入集群的TOKEN值过期
ES source code API call link source code analysis
剑指offer专项突击版 ---- 第2天
<urlopen error [Errno 11001] getaddrinfo failed>的解决、isinstance()函数初略介绍