Saturday, January 29, 2011

Primes, Sums of Primes, 2011 in C#

{

I had no idea:

2011 = 157 + 163 + 167 + 173 + 179 + 181 + 191 + 193 + 197 + 199 + 211

After learning that not only was 2011 was prime, but that it was the sum of consecutive primes, I sought to write some C# code that would demonstrate this. I wrote it in a functional style, meaning at some point to port it to F# – you'll recognize my in a forthcoming post on computing primes with F# which is actually an implementation of the algorithm I first worked through in the below C#.

Func<long[], IEnumerable<KeyValuePair<long, string>>> GenerateConsecutivePrimeSums = (primes) =>
{
List<KeyValuePair<long, string>> primeSums = new List<KeyValuePair<long, string>>();
for (int i = 0; i < primes.Count(); i++)
{
List<string> operands = new List<string>();
long primeSum = primes[i];
operands.Add(primeSum.ToString());
for (int j = i + 1; j < primes.Count(); j++)
{
primeSum += primes[j];
operands.Add(primes[j].ToString());
if (!primeSums.Any(ps => ps.Key == primeSum) && primes.Contains(primeSum))
{
primeSums.Add(new KeyValuePair<long, string>(primeSum, String.Join(" + ", operands.ToArray())));
}
}
}

return primeSums;
};

Action primesAndSums = () => {
// generate primes up to 2020
var primes = GeneratePrimes(2020);
// generate arrays of consecutive primes that add up to prime
var primesSummed = GenerateConsecutivePrimeSums(primes.OrderBy(a => a).ToArray());
// go through the summed primes (dictionary of prime as key, added numbers as value)
// Console.WriteLine formatted results
primesSummed
.OrderBy(ps => ps.Key)
.ToList()
.ForEach(ps => Console.WriteLine(ps.Key + " = " + ps.Value));
};

primesAndSums();


 



The code actually calculates sums of the primes it generates, click here for all the other primes which are sums of consecutive primes up to 2020:



}

No comments: