'How to display prime numbers in c#

How can I display the prime numbers between 1 and 100 in c#?



Solution 1:[1]

This might help:

using System;
namespace HelloWorld
{
    class Hello 
    {
        static void Main() 
        {
            System.Console.WriteLine("2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97");
        }
    }
}

Solution 2:[2]

Assuming you wish to find prime numbers, this is a standard question.

  1. Most efficient code for the first 10000 prime numbers?
  2. Most elegant way to generate prime numbers
  3. Prime number calculation fun
  4. Sieve of Eratosthenes [wikipedia]
  5. Sieve of Atkin [wikipedia]

Solution 3:[3]

Always fun to try to solve things like this as a one-liner... ;)

Enumerable.Range(2, 100).Where(n => Enumerable.Range(2, n - 2).Count(d => n % d == 0) == 0).ToList().ForEach(Console.WriteLine);

Solution 4:[4]

I think you should try to implement the sieve of Eratosthenes. There are more complicated sieves available, but thats usually a good version to start with.

Make sure you choose you datatypes correctly, and dont waste space by picking the wrong ones

If the requirement is as loose as in your question, you even might get away with a simple print statement that outputs a ready list of prime numbers ;) najmeddine already supplied the requiered information for you...

Solution 5:[5]

I suggest http://en.wikipedia.org/wiki/Sieve_of_Eratosthenes I wrote a method like this years ago in Turbo Pascal 7 (wow i'm that old!)

Solution 6:[6]

    IEnumerable<int> PrimeNumbers(int maxCap)
{
    yield return 2;
    yield return 3;

    for (var i = 4; i <= maxCap; i++)
    {
        var isPrime = true;
        for (var j = 2; j <= i / 2; j++)
        {
            if (i % j != 0) continue;
            isPrime = false;
            break;
        }

        if (isPrime) yield return i;
    }
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 sth
Solution 2 Community
Solution 3 Guffa
Solution 4 Heiko Hatzfeld
Solution 5
Solution 6 Levit Kanner