The primes 3, 7, 109, and 673, are quite remarkable. By taking any two primes and concatenating them in any order the result will always be prime. For example, taking 7 and 109, both 7109 and 1097 are prime. The sum of these four primes, 792, represents the lowest sum for a set of four primes with this property.
Find the lowest sum for a set of five primes for which any two primes concatenate to produce another prime.
A more brute-force approach is probably not possible to achieve...but it runs in less than 8 seconds so I'm not complaining! I also took for granted that the first result would be the lowest sum.
using System;
using System.Collections.Generic;
namespace project_euler
{
class Program
{
static void Main()
{
//Problem 60
DateTime start = DateTime.Now;
List<int> primes = GeneratePrimes(10000);
int sum;
bool finished = false;
for (int i = 0; i < primes.Count-4; i++)
{
string s = primes[i].ToString();
for (int j = i+1; j < primes.Count-3; j++)
{
string t = primes[j].ToString();
if (IsPrime(int.Parse(s + t)) &&
IsPrime(int.Parse(t + s)))
{
for (int k = j+1; k < primes.Count-2; k++)
{
string u = primes[k].ToString();
if (IsPrime(int.Parse(s + u)) &&
IsPrime(int.Parse(u + s)) &&
IsPrime(int.Parse(t + u)) &&
IsPrime(int.Parse(u + t)))
{
for (int l = k+1; l < primes.Count-1; l++)
{
string v = primes[l].ToString();
if (IsPrime(int.Parse(s + v))&&
IsPrime(int.Parse(t + v))&&
IsPrime(int.Parse(u + v))&&
IsPrime(int.Parse(v + s))&&
IsPrime(int.Parse(v + t))&&
IsPrime(int.Parse(v + u)))
{
for (int m = l+1; m < primes.Count; m++)
{
string w = primes[m].ToString();
if (IsPrime(int.Parse(s + w))&&
IsPrime(int.Parse(t + w))&&
IsPrime(int.Parse(u + w))&&
IsPrime(int.Parse(v + w))&&
IsPrime(int.Parse(w + s))&&
IsPrime(int.Parse(w + t))&&
IsPrime(int.Parse(w + u))&&
IsPrime(int.Parse(w + v)))
{
sum = primes[i] +
primes[j] +
primes[k] +
primes[l] +
primes[m];
//min = sum < min ? sum : min;
Console.WriteLine(sum);
Console.WriteLine(primes[i] + " " +
primes[j] + " " +
primes[k] + " " +
primes[l] + " " +
primes[m]);
finished = true;
break;
}
}
if (finished) break;
}
}
if (finished) break;
}
}
if (finished) break;
}
}
if (finished) break;
}
TimeSpan time = DateTime.Now - start;
Console.WriteLine("This took {0}", time);
Console.ReadKey();
}
public static bool IsPrime(int n)
{
if (n < 2) return false;
if (n == 2) return true;
for (long i = 2; i <= Math.Sqrt(n); i++)
if (n % i == 0) return false;
return true;
}
public static List<int> GeneratePrimes(int n)
{
var primes = new List<int> { 2, 3 };
for (int i = 5; i <= n; i += 2)
if (IsPrime(i))
primes.Add(i);
return primes;
}
}
}
Triple-click for answer: 26033
No comments:
Post a Comment