【ProjectEuler】ProjectEuler_010

// The sum of the primes below 10 is 2 + 3 + 5 + 7 = 17.
// 
// Find the sum of all the primes below two million.

using System;
using System.Collections.Generic;
using System.Text;

namespace projecteuler010
{
    class Program
    {
        static void Main(string[] args)
        {
            F2();
        }

        private static void F1()
        {
            Console.WriteLine(new System.Diagnostics.StackTrace().GetFrame(0).GetMethod());
            DateTime timeStart = DateTime.Now;

            long sum = 0;
            for (int i = 2; i < 2000000; i++)
            {
                if (isPrime(i))
                {
                    sum += i;
                }
            }
            Console.WriteLine(sum);
            Console.WriteLine("Total Milliseconds is " + DateTime.Now.Subtract(timeStart).TotalMilliseconds + "\n\n");
        }

        private static void F2()
        {
            Console.WriteLine(new System.Diagnostics.StackTrace().GetFrame(0).GetMethod());
            DateTime timeStart = DateTime.Now;

            long sum = 5;
            for (int i = 5; i < 2000000; i += 2)
            {
                if (isPrime(i))
                {
                    sum += i;
                }
            }
            Console.WriteLine(sum);
            Console.WriteLine("Total Milliseconds is " + DateTime.Now.Subtract(timeStart).TotalMilliseconds + "\n\n");
        }

        /// <summary>
        /// 判断是否为素数
        /// </summary>
        /// <param name="n"></param>
        /// <returns></returns>
        private static bool isPrime(long n)
        {
            if ((n % 2 == 0 && n != 2) || n <= 1)
            {
                return false;
            }

            long sqrtValue = long.Parse(Math.Sqrt(n).ToString().Split('.')[0]);

            for (int i = 3; i <= sqrtValue; i += 2)
            {
                if (n % i == 0)
                {
                    return false;
                }
            }
            return true;
        }
    }
}


/*
Void F1()
142913828922
Total Milliseconds is 3533.9487

Void F2()
142913828922
Total Milliseconds is 3461.9396

By GodMoon
*/

你可能感兴趣的:(String,Class)