Friday 17 April 2009

PROJECT EULER #51

Link to Project Euler problem 51

By replacing the 1st digit of *57, it turns out that six of the possible values: 157, 257, 457, 557, 757, and 857, are all prime.
By replacing the 3rd and 4th digits of 56**3 with the same digit, this 5-digit number is the first example having seven primes, yielding the family: 56003, 56113, 56333, 56443, 56663, 56773, and 56993. Consequently 56003, being the first member of this family, is the smallest prime with this property.
Find the smallest prime which, by replacing part of the number (not necessarily adjacent digits) with the same digit, is part of an eight prime value family.



using System;
using System.Collections.Generic;

namespace ProjectEuler
{
class Program
{
static void Main()
{
//Problem 51
string number = "";
int count = 0;
List<int> primes = GeneratePrimes(1000000);
while (primes[0] < 100000)
primes.Remove(primes[0]);
DateTime start = DateTime.Now;
foreach (int i in primes)
{
string s = i.ToString();
for (int j = 0; j < s.Length; j++)
{
char d = s[j];
count = 0;
for (int k = 0; k < 10; k++)
{
string t = s.Replace(d, char.Parse(k.ToString()));
if (IsPrime(int.Parse(t)) && int.Parse(t) > 100000)
count++;
}
if (count > 7)
{
number = s;
break;
}
}
if (count > 7)
break;
}
Console.WriteLine("the number {0} creates an 8 prime family", number);
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: 121313

No comments: