C#: Project Euler Solution to Problem 47

http://projecteuler.net/problem=47

The first two consecutive numbers to have two distinct prime factors are:

14 = 2 x 7
15 = 3 x 5

Find the first four consecutive integers to have four distinct primes factors. What is the first of these numbers?

static void Main(string[] args)
{
    LinkedList<int> threefactors = new LinkedList<int>();
    int n = 0;
    while (true)
    {
        n++;
        int factcount = 0;
        for (int i = 1; i <= n; i++)
        {
            if (n % i == 0 && isPrime(i))
                factcount++;
        }
        if (factcount == 4)
        {
            threefactors.AddLast(n);
            int lastn = (n - 1);
            int lastn2 = (n - 2);
            int lastn3 = (n - 3);
            if (threefactors.Contains(lastn)  && threefactors.Contains(lastn2) && threefactors.Contains(lastn3))
            {
                Console.WriteLine(n);
                Console.WriteLine(lastn);
                Console.WriteLine(lastn2);
                Console.WriteLine(lastn3);
                break;
            }
        }
    }
}
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 *