53-题目1440:Goldbach's Conjecture

哥德巴赫猜想程序实现
本文介绍了一个基于哥德巴赫猜想的程序设计案例,该程序能够找出给定偶数的所有素数对,满足素数对之和等于该偶数。通过定义素数检查函数并遍历所有可能的组合来解决问题。

http://ac.jobdu.com/problem.php?pid=1440

题目描述:

Goldbach's Conjecture: For any even number n greater than or equal to 4, there exists at least one pair of prime numbers p1 and p2 such that n = p1 + p2. 
This conjecture has not been proved nor refused yet. No one is sure whether this conjecture actually holds. However, one can find such a pair of prime numbers, if any, for a given even number. The problem here is to write a program that reports the number of all the pairs of prime numbers satisfying the condition in the conjecture for a given even number.

A sequence of even numbers is given as input. Corresponding to each number, the program should output the number of pairs mentioned above. Notice that we are interested in the number of essentially different pairs and therefore you should not count (p1, p2) and (p2, p1) separately as two different pairs.

简而言之,给一个数N([4,2^15]),找出它的素数对,即要满足P1+P2=N,求N有多少这样的素数对。

#include<iostream>
#include<fstream>
using namespace std;
#define MAX 105000

int PrimeNum(int n)   //判断是否是素数,返回1表示是素数,0非素数
{
	int i;
	for (i = 2; i < n; i++)
	{
		if (n % i == 0)
			break;
	}
	if (i == n)
		return 1;
	else
		return 0;
}

int main()
{
	int num, i, count, p1, p2;
	ifstream cin("data.txt");
	while (cin >> num && num != 0)
	{
		count = 0;
		for (i = 3; i <= num / 2; i++)
		{
			p1 = i;
			p2 = num - i;
			if (PrimeNum(p1) && PrimeNum(p2))  //两个都是素数
			{
				//cout << p1 << " " << p2 << endl;
				count++;
			}
		}
		cout << count << endl;
	}
	system("pause");
	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值