代码改变世界

质数算法

2013-08-14 10:30  莫耶  阅读(228)  评论(0编辑  收藏  举报
 1 class Program
 2 {
 3         static List<int> _PrimeFactos = null;
 4 
 5         static void Main(string[] args)
 6         {            
 7             var number = 0;
 8             string numberString = null;
 9             do
10             {
11                 Console.WriteLine("Input a range number:");
12                 numberString = Console.ReadLine();
13             } while (!int.TryParse(numberString, out number));
14 
15             //Performance Profiler 1
16             var watcher = new Stopwatch();
17             watcher.Start();
18             CalcPrimes1(number);
19             Console.WriteLine();
20             Console.WriteLine("Algorithm 1: {0}:{1}.{2}", watcher.Elapsed.Minutes, watcher.Elapsed.Seconds,watcher.Elapsed.Milliseconds);
21             watcher.Stop();
22 
23             //Performance Profiler 2
24             Console.WriteLine();
25             watcher.Restart();
26             CalcPrimes2(number);
27             Console.WriteLine();
28             Console.WriteLine("Algorithm 2: {0}:{1}.{2}", watcher.Elapsed.Minutes, watcher.Elapsed.Seconds, watcher.Elapsed.Milliseconds);
29             watcher.Stop();
30 
31             Console.ReadKey();
32         }
33 
34         static void CalcPrimes1(int number)
35         {
36             Console.Write("2 ");
37             for (var i = 3; i <= number; i += 2)
38             {
39                 if (IsPrime1(i))
40                     Console.Write(i + " ");
41             }
42         }
43 
44         static void CalcPrimes2(int number)
45         {
46             Console.Write("2 ");
47             for (var i = 3; i <= number; i += 2)
48             {
49                 if (IsPrime2(i))
50                     Console.Write(i + " ");
51             }
52         }
53 
54         static bool IsPrime1(int number)
55         {
56             if (number == 2)
57                 return true;
58             int squareRoot = Convert.ToInt32(Math.Sqrt(number));
59             for (var i = 2; i <= squareRoot; i++)
60                 if (number % i == 0)
61                     return false;
62             return true;
63         }
64 
65         static bool IsPrime2(int number)
66         {
67             if (_PrimeFactos == null)
68             {//init for prime factors
69                 _PrimeFactos = new List<int>();
70                 _PrimeFactos.Add(2);
71             }
72             foreach (var factor in _PrimeFactos)
73             {
74                 if (number % factor == 0)
75                     return false;
76             }
77             if (!_PrimeFactos.Contains(number))
78                 _PrimeFactos.Add(number);
79             return true;
80         }
81 }