### 素数c＃

=== 多谢你们。所以你建议最好先在Console应用程序中做到这一点？ 我使用控制台应用程序做了一个非常简单的“For Loop”示例，但是当我尝试在Windows窗体应用程序中执行它时，我不确定如何实现它。 我担心如果我继续在控制台中做示例，那么我将很难在Windows Form Apps中执行此操作。 你觉得怎么样？

====== 你好，再次，

``````        Console.WriteLine("Please enter your integer: ");
long yourInteger;

//displaying the first prime number and comparing it to the given integer
for (long i = 2; i <= yourInteger; i = i + 1)
{
//Controls i if its prime number or not
if ((i % 2 != 0) || (i == 2))
{
Console.Write("{0} ", i);
}

}
``````

#### 8 个答案:

• 如何从Windows应用程序中读取用户输入
• 如何生成范围内的素数
• 如何以您想要的方式编写输出

``````public IEnumerable<long> GetPrimes(int max)
{
var nonprimes = new bool[max + 1];

for (long i = 2; i <= max; i++)
{
if (nonprimes[i] == false)
{
for (var j = i * i; j <= max; j += i)
{
nonprimes[j] = true;
}

yield return i;
}
}
}
``````

``````var primes = SieveOfEratosthenes.GetPrimes(2000);
``````

...获得一个高达2000的IEnumerable素数。

``````using System;
class demo
{
static void Main()
{
int number;
Console.WriteLine("Enter Number you Should be Checked Number is Prime or not Prime");
for(int i =2;i {
if(number % i == 0)
{
Console.WriteLine("Entered number is not Prime");
break;
}
}
if(number % i !=0)
{
Console.WriteLine("Entered Number is Prime");
}

}
}
``````

``````    static List<int> GetPrimeNumbers(int maxNumber)
{
// seed the master list with 2
var list = new List<int>() {2};

// start at 3 and build the complete list
var next = 3;
while (next <= maxNumber)
{
// since even numbers > 2 are never prime, ignore evens
if (next % 2 != 0)

next++;
}

// create copy of list to avoid reindexing
var primes = new List<int>(list);

// index starts at 1 since the 2's were never removed
for (int i = 1; i < list.Count; i++)
{
var multiplier = list[i];
// FindAll Lambda removes duplicate processing
list.FindAll(a => primes.Contains(a) && a > multiplier)
.ForEach(a => primes.Remove(a * multiplier));
}

return primes;
}
``````