-
Notifications
You must be signed in to change notification settings - Fork 3
/
10311-GoldbachandEuler.cpp
executable file
·92 lines (80 loc) · 1.46 KB
/
10311-GoldbachandEuler.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
//
// 10311 - Goldbach and Euler.cpp
// Uva
//
// Created by Alexander Faxå on 2012-05-20.
// Copyright (c) 2012 __MyCompanyName__. All rights reserved.
//
#include <stdio.h>
#include <iostream>
#include <string.h>
#include <math.h>
#include <algorithm>
using namespace std;
#define MAXN 100000000
char prime[100000000];
// Calc primes up to MAXN, store in prime
void calcprimes()
{
memset(prime,255,sizeof(prime));
prime[0] = 0xFE;
for(int i = 1; i < 5000; i++)
{
if (prime[i>>3]&(1<<(i&7)))
{
for(int j = i + i + i + 1; j < MAXN/2; j += i + i + 1)
{
prime[j>>3]&=~(1<<(j&7));
}
}
}
}
bool isprime(long long n)
{
return prime[(n) >> 4] & ( 1<< (((n) >> 1) & 7));
}
int main()
{
calcprimes();
int n;
while (cin >> n)
{
if (n < 3)
{
cout << n << " is not the sum of two primes!" << endl;
continue;
}
if (n%2 == 1)
{
if (isprime(n-2))
cout << n << " is the sum of 2 and " << n-2 << "." << endl;
else
cout << n << " is not the sum of two primes!" << endl;
continue;
}
else
{
bool ok = false;
int i = n/2;
if(i%2==0)
i++;
for (; i >= 3; i-=2)
{
if (isprime(i) && isprime(n-i))
{
int p1 = min(i, n-i);
int p2 = max(i, n-i);
if(p1!=p2 && p1>1 && p2 > 1)
{
cout << n << " is the sum of " << p1 << " and " << p2 << "." << endl;
ok = true;
break;
}
}
}
if (!ok)
cout << n << " is not the sum of two primes!" << endl;
}
}
return 0;
}