C#: Project Euler Solution to Problem 37

Project Euler Problem 37

The number 3797 has an interesting property. Being prime itself, it is possible to continuously remove digits from left to right, and remain prime at each stage: 3797, 797, 97, and 7. Similarly we can work from right to left: 3797, 379, 37, and 3.

Find the sum of the only eleven primes that are both truncatable from left to right and right to left.

NOTE: 2, 3, 5, and 7 are not considered to be truncatable primes.

static void Main(string[] args)
{
    DateTime dt1 = DateTime.Now;
 
    int truncPrimeCount = 0;
    int truncSum = 0;
    for (int j = 1; j < 1000000; j++)
    {
        if (isPrime(j))
        {
            string specialPrimeNumer = "" + j;
            bool primedelims = true;
            while (primedelims == true)
            {
                for (int i = 1; i < specialPrimeNumer.Length; i++)
                {
                    int prime_chck = int.Parse(specialPrimeNumer.Remove(specialPrimeNumer.Length - i));
                    if (!isPrime(prime_chck))
                        primedelims = false;
                }
                for (int i = 1; i < specialPrimeNumer.Length; i++)
                {
                    int prime_chck = int.Parse(specialPrimeNumer.Remove(0, i));
                    if (!isPrime(prime_chck))
                        primedelims = false;
                }
 
                if (primedelims == true)
                {
                    truncPrimeCount++;
                    Console.WriteLine("Trunc prime #    : " + specialPrimeNumer);
                    if (truncPrimeCount > 4)
                        truncSum += int.Parse(specialPrimeNumer);
                    if (truncPrimeCount == 15)
                        j = 1000001;
                    primedelims = false;
                }
            }
        }
    }
    Console.WriteLine("                 Sum :" +truncSum);
    DateTime dt2 = DateTime.Now;
    Console.WriteLine("Time : " +(dt2 - dt1));
}
 
public static bool isPrime(int n)
{
    if (n == 1)
        return false;
    if (n == 2)
        return true;
    for (int i = 2; i < n; ++i)
    {
        if ((n % i) == 0)
            return false;
    }
    return true;
}

Leave a Reply

Your email address will not be published. Required fields are marked *