任意一个大于2的偶数,都可以分解为两个质数之和。编写一个程序,验证上述结论。
例如:输入16, 输出16=13+3
#include<iostream>
#include<cmath>
using namespace std;
bool isPrime( int num )
{
//两个较小数另外处理
if(num ==2|| num==3 )
return 1 ;
//不在6的倍数两侧的一定不是质数
if(num %6!= 1&&num %6!= 5)
return 0 ;
int tmp =sqrt( num);
//在6的倍数两侧的也可能不是质数
for(int i= 5; i <=tmp; i+=6 )
if(num %i== 0||num %(i+ 2)==0 )
return 0 ;
//排除所有,剩余的是质数
return 1 ;
}
int main()
{
int x;
cin>>x;
int i=2,j=x-i;
if(x%2==0){
while(i<=j){
if(isPrime(i)&&isPrime(j)){
cout<<x<<"="<<i<<"+"<<j<<endl;
return 0;
}
i++;j--;
}
cout<<"Can't do it."<<endl;
}else{
cout<<"The number is not even."<<endl;
}
return 1;
}
import random def zhi_number(k):#判断是否是质数 flag=True beichushu=2 while beichushu<=k/2: if k%beichushu==0: flag=False break else: beichushu+=1 return flag def qiuzhishu(n):#求某个数的质数集合列表 zhishu_list=list() chushu=2 while chushu<n: if zhi_number(chushu)==True: zhishu_list.append(chushu) chushu+=1 return zhishu_list def yanzheng(): name=random.randint(1,2**32) while name%2!=0: name=random.randint(1,2**32) # 随机生成一个偶数,范围很大,2的32次方 zhishuset=qiuzhishu(name) falg=False for name1 in zhishuset:#在质数集合里找第一个加数 for name2 in zhishuset:#找第二个加数 if name==name1+name2:#判断想加是否等于随机生成的偶数 falg=True break return falg print(yanzheng())
#include<math.h>
#include<stdio.h>
int isprime(int x)
{//判断一个数是否是质数
int start=2;
while(start*start<=x)
{//只需要试探到根号x就已经足够
if(x%start==0)
return 0;
else
start++;
}
return 1;
}
int main()
{
int num,explore = 2,sub_explore;//explore从最小的质数开始试探
printf("input an even number:");
scanf("%d",&num);
while(num%2)//如果输入的不是偶数就请求一个偶数
{
printf("erro!need an even number:\n");
scanf("%d",&num);
}
sub_explore = num-explore;
while(isprime(explore) && isprime(sub_explore))
//用while循环寻找两个质数之和
{
explore++;
sub_explore--;
if(sub_explore>explore)//定理被推翻!!!
printf("niubi!!!");
}
printf("%d can be broken down into %d and %d: ",num,explore,sub_explore);
return 1;
} def primality(n):
if n <= 102:
for a in range(2, n):
if pow(a, n - 1, n) != 1:
return False
else:
import random
for i in range(100):
a = random.randint(2, n - 1)
if pow(a, n - 1, n) != 1:
return False
return True
while True:
try:
A = int(input('Please input an even number:').strip())
if A=='':
break
elif A%2!=0:
print('Not even, please retry!')
continue
if A==4:
print('4 = 2 + 2')
continue
halfA,flag = int(A/2),False
# just need to check odd numbers, >=3
for S in range(3,halfA+1,2):
B = A - S
if primality(S) and primality(B):
flag = True
print('%d = %d + %d' %(A,S,B))
if not flag:
print('%d cannot be divided!' %A)
except:
break
会逐行打印出所有可能的结果(若仅统计数目,可自行参考修改) ——python 3.5
//任意大于2的偶数,都可以分解成两个质数之和#include<stdio.h>int Su(int n){int answer=1;for(int temp=2;temp*temp<n;temp++){if(n%temp==0)answer=0;}return answer;}int main(void){int a;printf("Please Input a Number:\n");scanf("%d",&a);while(a%2!=0||a<=2){printf("Wrong Input! Repeat:");scanf("%d",&a);}for(int temp=1;temp<a;temp++){if(Su(temp)&&Su(a-temp)){printf("Answer:%d %d\n",temp,a-temp);break;}}return 0;}