# Project Euler 3 - Largest Prime Factor - Solved with C#

The third Project Euler problem - Largest Prime Factor - is stated as follows. What is the largest prime factor of the number 600851475143?

using System;
using System.Linq;
using System.Collections.Generic;

public class Program
{
public static IEnumerable<long> Primes()
{
// Create a range between 2 and the closest we can get Infinity.
return Enumerable.Range(2, Int32.MaxValue - 1)
// Get all values which are only divisible by themself and 1.
.Where(x => Enumerable.Range(2, x-2).All(y => x % y != 0))
// Cast the values to long.
.Select(n => (long)n);
}

public static IEnumerable<long> PrimeFactors(long input)
{
// Get all primes...
long next = Primes()
// ... below the square root of input.
.TakeWhile(x => x <= Math.Sqrt(input))
// Find the first prime that input is divisble by.
.FirstOrDefault(x => input % x == 0);

if(next == default(long)){
// If we can't find a new factor, then input is the last factor.
return new long[]{input};
} else {
// Add the found factor to the list and recurse.
return new long[]{next}.Concat(PrimeFactors(input / next));
}
}

public static void Main()
{
long factor = PrimeFactors(600851475143).Max();
Console.WriteLine(factor);
}
}