-
Notifications
You must be signed in to change notification settings - Fork 0
/
Problem046.cs
96 lines (85 loc) · 2.11 KB
/
Problem046.cs
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
93
94
95
96
namespace ProjectEuler.Solutions
{
using System;
using System.Collections;
using System.Collections.Generic;
using NUnit.Framework;
using ProjectEuler.Helper;
/// <summary>
/// Goldbach's other conjecture.
/// It was proposed by Christian Goldbach that every odd composite number can be written as the sum of a prime and twice a square.
/// <para>9 = 7 + 2×1<sup>2</sup></para>
/// <para>15 = 7 + 2×2<sup>2</sup></para>
/// <para>21 = 3 + 2×3<sup>2</sup>2</para>
/// <para>25 = 7 + 2×3<sup>2</sup>2</para>
/// <para>27 = 19 + 2×2<sup>2</sup>2</para>
/// <para>33 = 31 + 2×1<sup>2</sup>2</para>
/// It turns out that the conjecture was false.
/// <para>What is the smallest odd composite that cannot be written as the sum of a prime and twice a square?</para>
/// </summary>
public class Problem046 : Problem
{
public override long Solution()
{
long number = 0;
const int upperbound = 200000;
List<int> primes = Primes.EratosthenesSieve(upperbound);
foreach (int nonPrime in ReversedEratosthenesSieve(upperbound))
{
if (number > 0)
{
break;
}
if (nonPrime % 2 != 0)
{
foreach (int prime in primes)
{
if (prime > nonPrime)
{
number = nonPrime;
break;
}
if (CanBeComposited(prime, nonPrime))
{
break;
}
}
}
}
return number;
}
private static bool CanBeComposited(int prime, int nonPrime)
{
double result = Math.Sqrt((double)(nonPrime - prime) / 2);
return result.Equals((int)result);
}
private static IEnumerable<int> ReversedEratosthenesSieve(int upperbound)
{
List<int> nonPrimes = new List<int>(upperbound);
BitArray bitArray = new BitArray(upperbound + 1, true);
for (int i = 2; i * i < upperbound; i++)
{
if (bitArray.Get(i))
{
for (int j = i * i; j < upperbound; j += i)
{
bitArray.Set(j, false);
}
}
}
for (int i = 2; i < upperbound; i++)
{
if (!bitArray.Get(i))
{
nonPrimes.Add(i);
}
}
return nonPrimes;
}
[Test]
public void TestForProblem()
{
Assert.AreEqual(5777, this.Solution());
}
}
}