Thursday 16 April 2009

PROJECT EULER #47

Link to Project Euler problem 47

The first two consecutive numbers to have two distinct prime factors are:
14 = 2 x 7

15 = 3 x 5
The first three consecutive numbers to have three distinct prime factors are:
644 = 2² x 7 x 23

645 = 3 x 5 x 43
646 = 2 x 17 x 19.
Find the first four consecutive integers to have four distinct primes factors. What is the first of these numbers?

Took me some time to work this one out. The hard work is done by the method distinctPrimeFactors which divides the number by the smallest prime factor, then checks to see if it can divide it again by this number. It increments only if the prime divisor is a new number.


using System;

namespace project_euler
{
class Program
{
static void Main()
{
//Problem 47
DateTime start = DateTime.Now;
int startNumber = 644;
while (true)
{
if (distinctPrimeFactors(startNumber)==4&&
distinctPrimeFactors(startNumber+1)==4&&
distinctPrimeFactors(startNumber+2)==4&&
distinctPrimeFactors(startNumber+3)==4)
{
break;
}
startNumber++;
}
Console.WriteLine(startNumber);

TimeSpan time = DateTime.Now - start;
Console.WriteLine("This took {0}", time);
Console.ReadKey();
}
public static int distinctPrimeFactors(int number)
{
int numFactors = 0;
int prime = 2;
bool newPrime = true;
while (!IsPrime(number))
if (number%prime == 0)
{
number /= prime;
if (newPrime)
numFactors++;
newPrime = false;
}
else
{
do
prime++; while (!IsPrime(prime));
newPrime = true;
}
numFactors++;
return numFactors;
}
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;
}
}
}

No comments: