欧拉计划 第3题

The prime factors of 13195 are 5, 7, 13 and 29.

What is the largest prime factor of the number 600851475143 ?

 

class Program
    {
        private static List<long> primes = new List<long>(10000);

        static void Main(string[] args)
        {
            /*
             * The prime factors of 13195 are 5, 7, 13 and 29.
             * What is the largest prime factor of the number 600851475143 ?
             */
            const long number = 600851475143;
            primes.Add(2);
            long max = 2;
            long x = number;
            for (long i = 2; i <= x; i = NextPrime())
            {
			    if(number % i == 0)
			    {
			        x /= i;
			        max = i;
			    }
			}
            Console.WriteLine(max);

        }

        private static long NextPrime()
        {
            long last = primes.Last();
            long n = last + 1;
            while (true)
            {
                foreach (var item in primes)
                {
                    if (n % item == 0)
                    {
                        goto LoopOut;
                    }
                }
                primes.Add(n);
                return n;

                LoopOut:
                n++;
            }
        }
    }

 

posted @ 2011-08-28 17:23  kiminozo  阅读(290)  评论(0编辑  收藏  举报