I see that there are a few other people who have tackled Project Euler Problem #3. I hope you're not all sick of that question yet. I've not taken a look at those yet (purposely), but am about to now.
I feel like I did a pretty good job on this one, but you tell me. How can I further improve this code? I'm particularly interested in how it could be made even faster, but it seems to already be a pretty quick implementation. My first version took over an hour, this one runs almost instantly. I'm also interested in how I could have used a List<T>
instead of an array, if you feel that would have been a better data structure.
The prime factors of 13195 are 5, 7, 13 and 29.
What is the largest prime factor of the number 600851475143 ?
Numbers.cs - 79 Lines
There are three functions: IsPrime
, IsFactor
, and PrimeFactors
.
namespace Challenges
{
public class Numbers
{
public static Boolean IsPrime(Int64 number)
{
if (number < 2)
{
return false;
}
if (number == 2)
{
return true;
}
if (number % 2 == 0)
{
return false;
}
double sqrtOfNumber = Math.Sqrt(number);
for (var index = 3; index <= sqrtOfNumber; index += 2) //skip even numbers
{
if (number % index == 0)
{
return false;
}
}
return true;
}
public static bool IsFactor(Int64 dividend, Int64 divisor)
{
return (dividend % divisor == 0);
}
public static Int64[] PrimeFactors(Int64 number)
{
Int64[] results = { };
Int64 maxDivisor = number / 2;
int index = 0;
for (Int64 divisor = 2; divisor < maxDivisor; divisor++ )
{
if (IsFactor(number,divisor) && IsPrime(divisor))
{
Array.Resize(ref results, results.Length + 1);
results[index] = divisor;
index++;
Int64 factor = number / divisor;
if (IsPrime(factor))
{
Array.Resize(ref results, results.Length + 1);
results[index] = factor;
break;
}
else
{
Int64[] recursiveResults = PrimeFactors(factor);
Array.Resize(ref results, results.Length + recursiveResults.Length);
for (int i = 0; i < recursiveResults.Length; i++)
{
results[index] = recursiveResults[i];
index++;
}
break;
}
}
}
return results;
}
}
}
Console Program
To prove it works, you can check my answer.
namespace Challenges
{
class ProjectEuler3Program
{
static void Main(string[] args)
{
const Int64 verybigint = 600851475143;
Int64[] factors = Numbers.PrimeFactors(verybigint);
Console.WriteLine((factors.Max()));
Console.WriteLine();
Console.WriteLine("Press enter to close...");
Console.ReadLine();
}
}
}
x = y * z
, what values ofz
maximisey
?) and return it straight away. \$\endgroup\$