Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 263453
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 11, 20262026-05-11T22:36:10+00:00 2026-05-11T22:36:10+00:00

What is the most elegant way to implement this function: ArrayList generatePrimes(int n) This

  • 0

What is the most elegant way to implement this function:

ArrayList generatePrimes(int n)

This function generates the first n primes (edit: where n>1), so generatePrimes(5) will return an ArrayList with {2, 3, 5, 7, 11}. (I’m doing this in C#, but I’m happy with a Java implementation – or any other similar language for that matter (so not Haskell)).

I do know how to write this function, but when I did it last night it didn’t end up as nice as I was hoping. Here is what I came up with:

ArrayList generatePrimes(int toGenerate)
{
    ArrayList primes = new ArrayList();
    primes.Add(2);
    primes.Add(3);
    while (primes.Count < toGenerate)
    {
        int nextPrime = (int)(primes[primes.Count - 1]) + 2;
        while (true)
        {
            bool isPrime = true;
            foreach (int n in primes)
            {
                if (nextPrime % n == 0)
                {
                    isPrime = false;
                    break;
                }
            }
            if (isPrime)
            {
                break;
            }
            else
            {
                nextPrime += 2;
            }
        }
        primes.Add(nextPrime);
    }
    return primes;
}

I’m not too concerned about speed, although I don’t want it to be obviously inefficient. I don’t mind which method is used (naive or sieve or anything else), but I do want it to be fairly short and obvious how it works.

Edit: Thanks to all who have responded, although many didn’t answer my actual question. To reiterate, I wanted a nice clean piece of code that generated a list of prime numbers. I already know how to do it a bunch of different ways, but I’m prone to writing code that isn’t as clear as it could be. In this thread a few good options have been proposed:

  • A nicer version of what I originally had (Peter Smit, jmservera and Rekreativc)
  • A very clean implementation of the sieve of Eratosthenes (starblue)
  • Use Java’s BigIntegers and nextProbablePrime for very simple code, although I can’t imagine it being particularly efficient (dfa)
  • Use LINQ to lazily generate the list of primes (Maghis)
  • Put lots of primes in a text file and read them in when necessary (darin)

Edit 2: I’ve implemented in C# a couple of the methods given here, and another method not mentioned here. They all find the first n primes effectively (and I have a decent method of finding the limit to provide to the sieves).

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-11T22:36:11+00:00Added an answer on May 11, 2026 at 10:36 pm

    Many thanks to all who gave helpful answers. Here are my implementations of a few different methods of finding the first n primes in C#. The first two methods are pretty much what was posted here. (The posters names are next to the title.) I plan on doing the sieve of Atkin sometime, although I suspect it won’t be quite as simple as the methods here currently. If anybody can see any way of improving any of these methods I’d love to know 🙂

    Standard Method (Peter Smit, jmservera, Rekreativc)

    The first prime number is 2. Add this to a list of primes. The next prime is the next number that is not evenly divisible by any number on this list.

    public static List<int> GeneratePrimesNaive(int n)
    {
        List<int> primes = new List<int>();
        primes.Add(2);
        int nextPrime = 3;
        while (primes.Count < n)
        {
            int sqrt = (int)Math.Sqrt(nextPrime);
            bool isPrime = true;
            for (int i = 0; (int)primes[i] <= sqrt; i++)
            {
                if (nextPrime % primes[i] == 0)
                {
                    isPrime = false;
                    break;
                }
            }
            if (isPrime)
            {
                primes.Add(nextPrime);
            }
            nextPrime += 2;
        }
        return primes;
    }
    

    This has been optimised by only testing for divisibility up to the square root of the number being tested; and by only testing odd numbers. This can be further optimised by testing only numbers of the form 6k+[1, 5], or 30k+[1, 7, 11, 13, 17, 19, 23, 29] or so on.

    Sieve of Eratosthenes (starblue)

    This finds all the primes to k. To make a list of the first n primes, we first need to approximate value of the nth prime. The following method, as described here, does this.

    public static int ApproximateNthPrime(int nn)
    {
        double n = (double)nn;
        double p;
        if (nn >= 7022)
        {
            p = n * Math.Log(n) + n * (Math.Log(Math.Log(n)) - 0.9385);
        }
        else if (nn >= 6)
        {
            p = n * Math.Log(n) + n * Math.Log(Math.Log(n));
        }
        else if (nn > 0)
        {
            p = new int[] { 2, 3, 5, 7, 11 }[nn - 1];
        }
        else
        {
            p = 0;
        }
        return (int)p;
    }
    
    // Find all primes up to and including the limit
    public static BitArray SieveOfEratosthenes(int limit)
    {
        BitArray bits = new BitArray(limit + 1, true);
        bits[0] = false;
        bits[1] = false;
        for (int i = 0; i * i <= limit; i++)
        {
            if (bits[i])
            {
                for (int j = i * i; j <= limit; j += i)
                {
                    bits[j] = false;
                }
            }
        }
        return bits;
    }
    
    public static List<int> GeneratePrimesSieveOfEratosthenes(int n)
    {
        int limit = ApproximateNthPrime(n);
        BitArray bits = SieveOfEratosthenes(limit);
        List<int> primes = new List<int>();
        for (int i = 0, found = 0; i < limit && found < n; i++)
        {
            if (bits[i])
            {
                primes.Add(i);
                found++;
            }
        }
        return primes;
    }
    

    Sieve of Sundaram

    I only discovered this sieve recently, but it can be implemented quite simply. My implementation isn’t as fast as the sieve of Eratosthenes, but it is significantly faster than the naive method.

    public static BitArray SieveOfSundaram(int limit)
    {
        limit /= 2;
        BitArray bits = new BitArray(limit + 1, true);
        for (int i = 1; 3 * i + 1 < limit; i++)
        {
            for (int j = 1; i + j + 2 * i * j <= limit; j++)
            {
                bits[i + j + 2 * i * j] = false;
            }
        }
        return bits;
    }
    
    public static List<int> GeneratePrimesSieveOfSundaram(int n)
    {
        int limit = ApproximateNthPrime(n);
        BitArray bits = SieveOfSundaram(limit);
        List<int> primes = new List<int>();
        primes.Add(2);
        for (int i = 1, found = 1; 2 * i + 1 <= limit && found < n; i++)
        {
            if (bits[i])
            {
                primes.Add(2 * i + 1);
                found++;
            }
        }
        return primes;
    }
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Ask A Question

Stats

  • Questions 156k
  • Answers 156k
  • Best Answers 0
  • User 1
  • Popular
  • Answers
  • Editorial Team

    How to approach applying for a job at a company ...

    • 7 Answers
  • Editorial Team

    How to handle personal stress caused by utterly incompetent and ...

    • 5 Answers
  • Editorial Team

    What is a programmer’s life like?

    • 5 Answers
  • Editorial Team
    Editorial Team added an answer Even if you update the mediator through notifications it would… May 12, 2026 at 10:53 am
  • Editorial Team
    Editorial Team added an answer $('option:selected', 'select').removeAttr('selected').next('option').attr('selected', 'selected'); Check out working code here http://jsbin.com/ipewe/edit May 12, 2026 at 10:53 am
  • Editorial Team
    Editorial Team added an answer You could use str_split, if you're not concerned with where… May 12, 2026 at 10:53 am

Related Questions

I'm calling a webservice that is returning an unknown quantity of images in the
I have implemented the IEquatable interface in a class with the following code. public
I'm working on a Rails web application, and it's currently being used by some
I am writing a LINQ provider to a hierarchal data source. I find it

Trending Tags

analytics british company computer developers django employee employer english facebook french google interview javascript language life php programmer programs salary

Top Members

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.