Question

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

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?

====== 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);
            }

        }
Was it helpful?

Solution

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

If you don't already have an IDE, then note that C# Express is free and will cover all of the above.

OTHER TIPS

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

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

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.

I discussed creating prime numbers using the Sieve of Eratosthenes on my blog here:

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.

All the code can be found on CodePlex at http://FSharpCSharp.codeplex.com.

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.

Here's a great "naive" prime number algorithm, that would be perfect for your needs: http://en.wikipedia.org/wiki/Sieve_of_Eratosthenes

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.

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.

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();
   }
}

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top