当前位置:网站首页>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;
}边栏推荐
- The TOKEN value of Kubernetes joining the cluster expires
- 剑指offer基础版 ----- 第25天
- 剑指offer基础版 --- 第22天
- 运用flask框架发送短信验证码的流程及具体代码
- 【JS面试题】面试官:“[1,2,3].map(parseInt)“ 输出结果是什么?答上来就算你通过面试
- Element concatenation operations in numpy and pytorch: stack, concatenat, cat
- The interviewer asked me how to divide the database and the table?Fortunately, I summed up a set of eight-part essays
- STM32 - DMA
- .NET-9. A mess of theoretical notes (concepts, ideas)
- 面试官,不要再问我三次握手和四次挥手
猜你喜欢
随机推荐
第7章 网络层第3次练习题答案(第三版)
Interviewer, don't ask me to shake hands three times and wave four times again
Temporal客户端模型
剑指offer专项突击版 --- 第 3 天
tf.keras.utils.get_file()
MySQL8.0.26安装配置教程(windows 64位)
With MVC, why DDD?
CentOS7 - yum install mysql
【JS面试题】面试官:“[1,2,3].map(parseInt)“ 输出结果是什么?答上来就算你通过面试
C语言指针详解
The TOKEN value of Kubernetes joining the cluster expires
剑指offer专项突击版 ---第 5 天
账号或密码多次输入错误,进行账号封禁
Flink sink redis 写入Redis
快速掌握并发编程 --- 基础篇
Input length must be multiple of 8 when decrypting with padded cipher
C语言的文件操作(一)
Sword Point Offer Special Assault Edition ---- Day 2
matlab simulink欠驱动水面船舶航迹自抗扰控制研究
剑指offer专项突击版 ---- 第 6 天









