质数 c#
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/886540/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
prime numbers c#
提问by tintincutes
I'm new to C#. And I would like to program something like, displaying the prime numbers in a listbox if user will input any integer in the textbox. (that means, if they write 10, it will display the prime numbers from 0-10, or 20 from 0-20, etc).
我是 C# 的新手。我想编写类似的程序,如果用户将在文本框中输入任何整数,则在列表框中显示素数。(这意味着,如果他们写 10,它将显示 0-10 中的质数,或 0-20 中的 20,等等)。
What should I consider first, before I do the programming? I know there are many examples in the internet, but first I would like to know what will I need?
在进行编程之前,我应该首先考虑什么?我知道网上有很多例子,但首先我想知道我需要什么?
Thanks for the tip;-)
谢谢你的提示;-)
=== Thanks guys. So you're suggesting that it's better to do it first in the Console application? I did an example of "For Loop" using Console Application a very simple one, but then when I tried to do it in the Windows Form Application, I'm not sure how to implement it. I'm afraid that if I keep doing examples in the Console, then I'll have difficulty to do it in Windows Form Apps. What do you think?
=== 谢谢各位。所以您建议最好先在控制台应用程序中执行此操作?我使用控制台应用程序做了一个非常简单的“For 循环”示例,但是当我尝试在 Windows 窗体应用程序中执行此操作时,我不确定如何实现它。恐怕如果我继续在控制台中做示例,那么在 Windows Form Apps 中我将很难做到。你怎么认为?
====== Hello again,
====== 你好,
I need some feedback with my code:
我的代码需要一些反馈:
Console.WriteLine("Please enter your integer: ");
long yourInteger;
yourInteger = Int32.Parse(Console.ReadLine());
//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);
}
}
采纳答案by Marc Gravell
Well, first of all I'd think about how to find prime numbers, and write that in a console app that reads a line, does the math, and writes the results (purely because that is the simplest thing you can do, and covers the same parsing etc logic you'll need later).
好吧,首先我会考虑如何找到质数,然后将其写入控制台应用程序中,该应用程序读取一行,进行数学运算并写入结果(纯粹是因为这是您可以做的最简单的事情,并且涵盖稍后需要的相同解析等逻辑)。
When you are happy with the prime number generation, then look at how to do winforms - how to put a listbox, textbox and button on a form; how to handle the click event (of the button), and how to read from the textbox and write values into the listbox. Your prime code should be fairly OK to take "as is"...
当您对质数生成感到满意时,再看看如何做 winforms - 如何在表单上放置列表框、文本框和按钮;如何处理(按钮的)单击事件,以及如何从文本框读取并将值写入列表框。您的主要代码应该可以“按原样”使用......
If you don't already have an IDE, then note that C# Expressis free and will cover all of the above.
如果您还没有 IDE,请注意C# Express是免费的,它将涵盖以上所有内容。
回答by Jon Skeet
You'll need to know:
你需要知道:
- How to read user input from a Windows application
- How to generate prime numbers within a range
- How to write output in the way that you want
- 如何从 Windows 应用程序读取用户输入
- 如何在一个范围内生成素数
- 如何以您想要的方式编写输出
I strongly suggest that you separate these tasks. Once you've got each of them working separately, you can put them together. (Marc suggests writing a console app for the prime number section - that's a good suggestion if you don't want to get into unit testing yet. If you've used unit testing in other languages, it's reasonably easy to get up and running with NUnit. A console app will certainly be quicker to get started with though.)
我强烈建议您将这些任务分开。一旦你让它们分别工作,你就可以把它们放在一起。(Marc 建议为质数部分编写一个控制台应用程序 - 如果您还不想进行单元测试,这是一个很好的建议。如果您使用过其他语言的单元测试,则相当容易上手和运行NUnit。不过,控制台应用程序肯定会更快上手。)
In theory, for a potentially long-running task (e.g. the user inputs 1000000 as the first number) you should usually use a background thread to keep the UI responsive. However, I would ignore that to start with. Be aware that while you're computing the primes, your application will appear to be "hung", but get it working at all first. Once you're confident with the simple version, you can look at BackgroundWorker
and the like if you're feeling adventurous.
理论上,对于可能需要长时间运行的任务(例如,用户输入 1000000 作为第一个数字),您通常应该使用后台线程来保持 UI 响应。但是,一开始我会忽略它。请注意,当您计算素数时,您的应用程序看起来会“挂起”,但首先要让它工作。一旦您对简单版本充满信心,BackgroundWorker
如果您喜欢冒险,就可以查看等等。
回答by toxvaerd
Here's a great "naive" prime number algorithm, that would be perfect for your needs: http://en.wikipedia.org/wiki/Sieve_of_Eratosthenes
这是一个很棒的“天真”素数算法,非常适合您的需求:http: //en.wikipedia.org/wiki/Sieve_of_Eratosthenes
回答by Spoike
Here is a response to the edit:
以下是对编辑的回应:
Thanks guys. So you're suggesting that it's better to do it first in the Console application? I did an example of "For Loop" using Console Application a very simple one, but then when I tried to do it in the Windows Form Application, I'm not sure how to implement it. I'm afraid that if I keep doing examples in the Console, then I'll have difficulty to do it in Windows Form Apps. What do you think?
谢谢你们。所以您建议最好先在控制台应用程序中执行此操作?我使用控制台应用程序做了一个非常简单的“For 循环”示例,但是当我尝试在 Windows 窗体应用程序中执行此操作时,我不确定如何实现它。恐怕如果我继续在控制台中做示例,那么在 Windows Form Apps 中我将很难做到。你怎么认为?
If you want to present the prime numbers as a windows forms application then you need to design the user interface for it as well. That is a bit overkill for such a small problem to be solved. The easiest design you can do is to fill up a ListBox
in your form (example).
如果您想将质数显示为 Windows 窗体应用程序,那么您还需要为其设计用户界面。要解决这么小的问题,这有点矫枉过正。您可以做的最简单的设计是ListBox
在表单中填写 a (示例)。
If you're really keen on learning Windows Forms or WPF then there are several resourcesfor this.
如果您真的很想学习 Windows Forms 或 WPF,那么这里有几个资源。
回答by Martin Peck
I discussed creating prime numbers using the Sieve of Eratostheneson my blog here:
我在我的博客上讨论了使用埃拉托色尼筛法创建素数:
http://blogs.msdn.com/mpeck/archive/2009/03/03/Solving-Problems-in-CSharp-and-FSharp-Part-1.aspx
http://blogs.msdn.com/mpeck/archive/2009/03/03/Solving-Problems-in-CSharp-and-FSharp-Part-1.aspx
The code looks like this...
代码看起来像这样......
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;
}
}
}
With this code you can write statements like this...
使用此代码,您可以编写这样的语句...
var primes = SieveOfEratosthenes.GetPrimes(2000);
... to get an IEnumerable of primes up to 2000.
...获得最多 2000 的素数的 IEnumerable。
All the code can be found on CodePlex at http://FSharpCSharp.codeplex.com.
所有代码都可以在http://FSharpCSharp.codeplex.com上的 CodePlex 上找到。
The code is "as is" and so you should look at it to determine whether it suits your needs, whether you need to add error checking etc, so treat it as a sample.
代码是“原样”,因此您应该查看它以确定它是否适合您的需求,是否需要添加错误检查等,因此请将其视为示例。
回答by Joel Cochran
I was recently writing a routine to implement Sieve Of Eratosthenes and came across this thread. Just for the archives, here is my implementation:
我最近正在编写一个例程来实现 Eratosthenes 的筛分,并遇到了这个线程。仅用于存档,这是我的实现:
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)
list.Add(next);
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;
}
You could always seed it with "1, 2" if you needed 1 in your list of primes.
如果您的素数列表中需要 1,您总是可以用“1, 2”作为种子。
回答by Guru Bhai McClane Subodh Jain
using System;
class demo
{
static void Main()
{
int number;
Console.WriteLine("Enter Number you Should be Checked Number is Prime or not Prime");
number = Int32.Parse(Console.ReadLine());
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");
}
Console.ReadLine();
}
}
回答by Guru Bhai McClane Subodh Jain
Your approach is entirely wrong. Prime numbers are absolute and will never change. Your best bet is to pre-generate a long list of prime numbers. Then come up with an algorithm to quickly look up that number to determine if it is on the list. Then in your case (since you want to list all in the given range just do so). This solution will be much faster than any prime number finding algorithm implemented during run-time. If the integer entered is greater than your list then you can always implement the algorithm starting at that point.
你的做法是完全错误的。质数是绝对的,永远不会改变。最好的办法是预先生成一长串质数。然后想出一个算法来快速查找该数字以确定它是否在列表中。然后在您的情况下(因为您想列出给定范围内的所有内容,只需这样做)。该解决方案将比在运行时实现的任何质数查找算法快得多。如果输入的整数大于您的列表,那么您始终可以从该点开始实施算法。