The problem statement is as follows. I feel as if my code can be improved but I'm not able to see how to do so. Is there merit in removing {}
on the if
blocks? Since I'm new, could that unintentionally lead to bugs if I forget that only a single instruction can be executed?
The prime factors of 13195 are 5, 7, 13 and 29.
What is the largest prime factor of the number 600851475143 ?
class Program
{
static void Main(string[] args)
{
Console.WriteLine(LargestPrimeFactor(600851475143));
Console.ReadLine();
}
static long LargestPrimeFactor(long number)
{
long largestFactor = 1;
for (long i = 2; i<= Math.Sqrt(number); i++)
{
if (IsFactorOf(number, i))
{
if (IsPrime(i))
{
largestFactor = i;
}
while (number > 1 && IsFactorOf(number, i))
{
number /= i;
}
}
}
if (number == 1)
{
return largestFactor;
}
else
{
return number;
}
}
static bool IsFactorOf(long numerator, long denominator)
{
return numerator % denominator == 0 || numerator == denominator;
}
static bool IsPrime(long value)
{
int maxPossibleRoot = (int)Math.Sqrt(value);
for (int i = 2; i <= maxPossibleRoot; i++)
{
if (value % i == 0)
{
return false;
}
}
return true;
}
}