prime numbers c#

前端 未结 8 1674

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 wri

相关标签:
8条回答
  • 2020-12-11 19:12

    I was recently writing a routine to implement Sieve Of Eratosthenes and came across this thread. Just for the archives, here is my implementation:

        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.

    0 讨论(0)
  • 2020-12-11 19:13

    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?

    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).

    If you're really keen on learning Windows Forms or WPF then there are several resources for this.

    0 讨论(0)
提交回复
热议问题