程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> .NET網頁編程 >> C# >> C#入門知識 >> C#中采用迭代的方法獲取素數,范圍自定

C#中采用迭代的方法獲取素數,范圍自定

編輯:C#入門知識

[csharp] 
<pre name="code" class="csharp">Primes.cs文件</pre> 
<pre></pre> 
<pre name="code" class="csharp">using System; 
using System.Collections; 
using System.Collections.Generic; 
using System.Linq; 
using System.Text; 
 
namespace ConsoleApplication1 

    public class Primes 
    { 
        private long min; 
        private long max; 
 
        public Primes() : this(2, 100) 
        { } 
        public Primes(long minimum, long maximum) 
        { 
            if (min < 2) 
                min = 2; 
            else 
                min = minimum; 
            max = maximum; 
        } 
        public IEnumerator GetEnumerator() 
        { 
            for (long possiblePrime = min; possiblePrime <= max; possiblePrime++) 
            { 
                bool isPrime = true; 
                for (long possibleFactor = 2; possibleFactor <= (long)Math.Floor(Math.Sqrt(possiblePrime)); possibleFactor++) 
                { 
                    long remainderAfterDivision = possiblePrime % possibleFactor; 
                    if (remainderAfterDivision == 0) 
                    { 
                        isPrime = false; 
                        break; 
                    } 
                } 
                if (isPrime) 
                { 
                    yield return possiblePrime; 
                } 
            } 
        } 
    } 

</pre><pre name="code" class="csharp"><pre name="code" class="csharp">Program.cs文件</pre> 
<pre></pre> 
<pre name="code" class="csharp">using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Text; 
 
 
namespace ConsoleApplication1 

    class Program 
    { 
        static void Main(string[] args) 
        { 
           <span style="color:#ff0000;"> Primes primesFrom2To1000 = new Primes(2, 10000);  //此處定義范圍</span> 
            foreach (long i in primesFrom2To1000) 
                Console.Write("{0}",i+"\t"); 
            Console.WriteLine(); 
            Console.ReadKey(); 
        } 
    } 

</pre><br> 
 
</pre> 

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved