I'm trying to solve Project Euler problem #3, which asks:
The prime factors of 13195 are 5, 7, 13 and 29. What is the largest prime factor of the number 600851475143 ?
Can you please review the code and suggests improvements?
namespace FullPractice
{
public class PrimeFactorFinder
{
private readonly HashSet<int> _myPrimeFactors = new HashSet<int>();
private long _myNumber;
public void PrimeFactors(long number)
{
_myNumber = number;
FindPrimeFactors();
DisplayAllPrimeFactors();
ShowLargestPrimeFactor();
}
private void ShowLargestPrimeFactor()
{
Console.WriteLine("\nLargest Prime Factor = {0}",_myPrimeFactors.Last());
}
private void FindPrimeFactors()
{
long temp = _myNumber;
int primeNumber = 2;
while (temp != 1)
{
if (temp%primeNumber == 0)
{
_myPrimeFactors.Add(primeNumber);
temp = temp/primeNumber;
}
else
{
primeNumber = GetPrimeNumberAfter(primeNumber);
}
}
}
private void DisplayAllPrimeFactors()
{
Console.WriteLine("All prime factors of {0} are : ", _myNumber);
foreach (var primeFactor in _myPrimeFactors)
{
Console.Write("{0},", primeFactor);
}
}
private int GetPrimeNumberAfter(int primeNumber)
{
var next = primeNumber + 1;
while (true)
{
if (IsPrime(next))
{
return next;
}
next++;
}
}
private bool IsPrime(int number)
{
if (number%2 == 0)
{
return false;
}
var sqaureRoot = (int)Math.Sqrt(number);
for (int divisor = 3; divisor < sqaureRoot; divisor += 2)
{
if (number%divisor == 0)
{
return false;
}
}
return true;
}
}
}