C++版浙大PAT乙级1007(20分)

本文介绍了一款质数对计数器程序的两种实现方式,该程序能够计算出小于等于给定数值的所有质数对,其中每个质数对的差值为2。通过对比两个版本的代码,读者可以了解到如何优化算法以提高程序效率。

https://pintia.cn/problem-sets/994805260223102976/problems/994805317546655744

3.9改进版本

#include<iostream>
#include<math.h>
using namespace std;

bool isPrime(int num){
	for(int i=2; i<=sqrt(num); i++){
		if(num%i==0){
			return false;
		}
	}
	return true;
}

int main(){
	int n, pre = 2, count = 0;
	cin >> n;
	for(int i=2; i<=n; i++){
		if(isPrime(i)){
			if(i-pre == 2)
				count ++;
			pre = i;
		}
	}
	cout << count << endl;
	return 0;
}

原版

这题的意思是,输入一个正整数n,对于不超过n的质数中,有多少个相差为2的质数对。 

#include<iostream>
#include<math.h>
using namespace std;

// 判断质数
bool isPrime(int num){
	for(int n=2; n<=sqrt(num); n++){
		if(num % n == 0){
			return false;
		}
	}
	return true;
}

int main(){
	int a, count = 0;
	cin >> a;
	if(a < 5){
		cout << 0;
		return 0;
	}
	for(int odd=3, pre=3; odd<=a; odd+=2){
		if(isPrime(odd)){
			if(odd-pre==2)
				count ++;
			pre = odd;
		}
	}
	cout << count;
	return 0;
}

 

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值