1. 程式人生 > >程式基本演算法習題解析 驗證任意一個大於5的奇數可以表示為3個素數之和

程式基本演算法習題解析 驗證任意一個大於5的奇數可以表示為3個素數之和

題目:

驗證任意一個大於5的奇數可以表示為3個素數之和。

附上程式碼:

// Chapter1_9.cpp : Defines the entry point for the application.
// 驗證任意一個大於5的奇數可以表示為3個素數之和

#include "stdafx.h"
#include<iostream>
#include<math.h>
using namespace std;
//判斷是否為素數(輸入大於2)
int isPrime(int x)
{
	int i=2,bound = int(sqrt(float(x)));//只需判斷到平方根即可
	while(i<=bound)
	{
		if(x%i == 0)
			return 0;  //不為素數,返回0
		i++;
	}
	return 1;  //為素數,返回1
}
int main()
{
	int odd,x,y,z; //odd為使用者輸入資料,x,y,z分別為三個數
	cout << "input an odd bigger than 5: ";
	cin >> odd;
	for(x=3;x<odd;x++)
	{
		for(y=3;y<odd;y++)
		{
			for(z=3;z<odd;z++)
			{
				//當x,y,z均為素數且其和等於使用者輸入的數時
				if(isPrime(x) && isPrime(y) && isPrime(z) && (odd == x+y+z))
					cout << odd << " = " << x << " + " << y << " + " << z << endl;
			}
		}
	}
	system("pause");
	return 0;
}

執行結果如下: