codeforces 324# D. Dima and Lisa (素数问题)

来源:互联网 发布:无线破解密码软件 编辑:程序博客网 时间:2024/06/08 08:18

题目:http://codeforces.com/contest/584/problem/D

题意:找1个或2个或3个素数,使得找的素数的和为n(n<1 000 000 000)。

D. Dima and Lisa
time limit per test
1 second
memory limit per test
256 megabytes
input
standard input
output
standard output

Dima loves representing an odd number as the sum of multiple primes, and Lisa loves it when there are at most three primes. Help them to represent the given number as the sum of at most than three primes.

More formally, you are given an odd numer n. Find a set of numbers pi (1 ≤ i ≤ k), such that

  1. 1 ≤ k ≤ 3
  2. pi is a prime

The numbers pi do not necessarily have to be distinct. It is guaranteed that at least one possible solution exists.

Input

The single line contains an odd number n (3 ≤ n < 109).

Output

In the first line print k (1 ≤ k ≤ 3), showing how many numbers are in the representation you found.

In the second line print numbers pi in any order. If there are multiple possible solutions, you can print any of them.

Sample test(s)
input
27
output
35 11 11
Note

A prime is an integer strictly larger than one that is divisible only by one and by itself.

分析:由于相邻两个素数的距离很小并且任何一个大于6的偶数都可以用两个素数的和表示可以先找一个比n小的最大的素数p1,那么n-p1就很小而且n-p1为偶数,然后直接枚举剩下一个或者两个素数就行了。

代码:

#include <iostream>#include <cstdio>using namespace std;bool isprime(int x){if(x<2)return false;if(x==2)return true;for(int i=2;i*i<=x;i++)if(x%i==0)return false;return true;}int Find(int x){for(int i=x-2;i>=0;i--)if(isprime(i))return i;return -1;}int main(){int n,i,j;int p,ans[10];cin>>n;if(isprime(n)){printf("1\n");printf("%d\n",n);return 0;}if(n==3){printf("1\n");printf("%d\n",3);return 0;}else if(n==4){printf("2\n");printf("2 2\n");return 0;}else if(n==5){printf("2\n");printf("2 3\n");return 0;}else if(n==6){printf("2\n");printf("3 3\n");return 0;}else if(n==7) {printf("3\n");printf("2 2 3\n");return 0;}else{p=0;ans[p++]=Find(n);n-=ans[p-1];for(int i=2;i<=n;i++)for(int j=2;j<=n;j++)if(isprime(i) && isprime(j) && i+j==n){printf("3\n"); printf("%d %d %d\n",ans[0],i,j);return 0;}else if(isprime(i) && i==n){printf("2\n");printf("%d %d\n",ans[0],i);return 0;}printf("-1\n");}return 0;} 



0 0
原创粉丝点击