Project Euler

Project Euler Problem 37

steloflute 2012. 6. 9. 00:08

Problem 37

14 February 2003

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.


Answer:
748317

 

 

C#

 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Numerics;
using System.IO;

namespace Euler {
    class Program {
        static bool isPrime(int value) {
            if (value <= 1) return false;
            for (int i = 2; i * i <= value; i++) {
                if (value % i == 0) return false;
            }
            return true;
        }

        static void Main(string[] args) {
            int x = 10;
            int count = 0;
            int sum = 0;
            while (true) {
                string strX = x.ToString();
                for (int i = 0; ; i++) {
                    if (!isPrime(Convert.ToInt32(strX))) goto Next;
                    if (strX.Length <= 1) break;
                    strX = strX.Substring(1);
                }
                strX = x.ToString();
                strX = strX.Substring(0, strX.Length - 1);
                for (int i = 0; ; i++) {
                    if (!isPrime(Convert.ToInt32(strX))) goto Next;
                    if (strX.Length <= 1) break;
                    strX = strX.Substring(0, strX.Length - 1);
                }
                count++;
                sum += x;
                Console.WriteLine(x);
                if (count >= 11) break;                
            Next:
                x++;
            }
            Console.WriteLine(sum);
        }
    }
}



'Project Euler' 카테고리의 다른 글

Project Euler Problem 39  (0) 2012.06.09
Project Euler Problem 38  (0) 2012.06.09
Project Euler Problem 36  (0) 2012.06.09
Project Euler Problem 35  (0) 2012.06.09
Project Euler Problem 34  (0) 2012.06.09