素数和为偶数
从4开始的所有偶数都可以表示为两个素数之和。有时一个数字可以有多个素数组合之和。
例如,数字10 = (5 + 5) 和 (7 + 3)
此算法将找到给定数字的所有素数和组合。当一个数字x是素数时,我们才会检查(number - x)是否也是素数,如果是,则x和(number – x)之和表示该偶数。
输入和输出
Input: Even number: 70 Output: Prime sums 70 = 3 + 67 70 = 11 + 59 70 = 17 + 53 70 = 23 + 47 70 = 29 + 41
算法
dispPrimeSum(num)
输入 − 偶数。
输出:使用一些素数之和显示该数字。
Begin if num is odd, then exit for i := 3 to num/2, do if i is prime, then if (num - i) is prime, then display ‘’num = i + (num – i)” done End
示例
#include<iostream> using namespace std; int isPrime(int number) { //check whether number is prime or not int lim; lim = number/2; for(int i = 2; i<=lim; i++) { if(number % i == 0) return 0; //The number is not prime } return 1; //The number is prime } void displayPrimeSum(int num) { string res; if(num%2 != 0) { //when number is an odd number cout << "Invalid Number"; exit(1); } for(int i = 3; i <= num/2; i++) { if(isPrime(i)) { //if i is a prime number if(isPrime(num-i)) { //num - i is also prime, then cout << num <<"= "<<i << " + "<<(num-i)<<endl; } } } } main() { int num; cout << "Enter an even number: "; cin >> num; displayPrimeSum(num); }
输出
Enter an even number: 70 70 = 3 + 67 70 = 11 + 59 70 = 17 + 53 70 = 23 + 47 70 = 29 + 41
广告