O. Summation of Four Primes
题目描述
Euler proved in one of his classic theorems that prime numbers are infinite in number. But can every number be expressed as a summation of four positive primes? I don’t know the answer. May be you can help!!! I want your solution to be very efficient as I have a 386 machine at home. But the time limit specified above is for a Pentium III 800 machine. The definition of prime number for this problem is “A prime number is a positive number which has exactly two distinct integer factors”. As for example 37 is prime as it has exactly two distinct integer factors 37 and 1.
输入
The input contains one integer number N (N≤10000000) in every line. This is the number you will have to express as a summation of four primes. Input is terminated by end of file.
输出
For each line of input there is one line of output, which contains four prime numbers according to the given condition. If the number cannot be expressed as a summation of four prime numbers print the line ‘Impossible.’ in a single line. There can be multiple solutions. Any good solution will be accepted.
样例:
输入:
24
36
46
输出:
3 11 3 7
3 7 13 13
11 11 17 7
题目大意:给你一个整数,问是否可以分解为4个素数。可以则输出,不可以则输出”Impossible.“看清楚这里有个实心点
思路:2是最小的素数,且2是唯一的偶素数,小于8的直接pass掉;
大于等于8的数 (一定可以分解成4个素数) 分为两种情况:
若是奇数,可以用 2和3 直接得到2个拆解数,在(n-2-3)(可知剩下的数为偶数,一个偶数(大于2)可以分解为两个素数的和) 中再拆解分成两个数 判断是否都是素数(埃式筛 筛选素数) ,若都是素数 break,输出;
若是偶数,用两个2 作为两个拆解数,在(n-2-2) (可知剩下的数为偶数,一个偶数(大于2)可以分解为两个素数的和) 中再拆解分成两个数,剩下的操作同上;
代码:
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
const int maxn=10000010;
int isprime[maxn];
void judge() {
int i,j;
for(i=2; i<maxn; i++) isprime[i]=1;
for(i=2; i<maxn; i++)
if(isprime[i])
for(j=i*2; j<maxn; j+=i)
isprime[j]=0;
}
int main() {
std::ios::sync_with_stdio(false);
int n,s=0;
judge();
while(scanf("%d",&n)!=EOF) {
if(n<8) cout<<"Impossible."<<endl;
else {
if(n%2) {
cout<<2<<" "<<3;
int num=n-2-3;
for(int i=2; i<=n; i++) {
if(isprime[i]&&isprime[num-i]) {
cout<<" "<<i<<" "<<num-i<<endl;
break;
}
}
} else {
cout<<2<<" "<<2;
int num=n-2-2;
for(int i=2; i<=n; i++) {
if(isprime[i]&&isprime[num-i]) {
cout<<" "<<i<<" "<<num-i<<endl;
break;
}
}
}
}
}
return 0;
}