I just started doing the Project Euler challenges and right now I'm on Challenge #3 - The largest prime factor of 600851475143.I wrote some code and tried to optimize it based on some other Stack Overflow users' advice.What I got is this code which does its job, but I think it takes longer than it should - calculating high numbers like 600851475143 takes forever!Am I in the right way? How could I optimize it?using System;namespace ProjectEuler_LargestPrimeFactor{    class Program    {        static long numberToFactor = 600851475143;        static void Main(string[] args)        {            Console.WriteLine(LargestPrimeFactorOf(numberToFactor) +  is the largest prime factor of  + numberToFactor);            Console.ReadKey();        }        static long LargestPrimeFactorOf(long n)        {            long lastPrimeFactor = 0;            for (long i = 2; i < n; i++)            {                if (isPrime(i) && n % i == 0)                {                    lastPrimeFactor = i;                    Console.WriteLine(i +  is a prime factor of  + n);                }            }            return lastPrimeFactor;        }        static bool isPrime(long n)        {            if (n == 2) return true;            if ((n > 2 && n % 2 == 0) || n == 1) return false;            for (long i = 2; i <= Math.Floor(Math.Sqrt(n)); ++i)            {                if (n % i == 0) return false;            }            return true;        }    }}
Project Euler #3 in C# - largest prime factor
c#;performance;programming challenge;primes
static bool isPrime(long n){    if (n == 2) return true;    if ((n > 2 && n % 2 == 0) || n == 1) return false;    for (long i = 2; i <= Math.Floor(Math.Sqrt(n)); ++i)    {        if (n % i == 0) return false;    }    return true;}The above code is inefficient.performance: since n doesn't change, you should only compute n once.performance: don't check even numbers in the for loop, since they will never divide evenly.readability: don't mix the n == 1 case with the n is even case.naming: method names start with a capital letter.Improved code:static bool IsPrime(long n){    if (n < 4) return n > 1;    if (n % 2 == 0 || n % 3 == 0) return false;    long limit = (long) Math.Sqrt(n);    for (long i = 5; i <= limit; i += 2)    {        if (n % i == 0) return false;    }    return true;}