HiveBrain v1.2.0
Get Started
← Back to all entries
patterncsharpMinor

Getting all primes between 0 - n

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
betweengettingprimesall

Problem

Is there a faster way to get all primes between 0 - n?

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Numerics;

namespace myPrime
{
    public class simplePrimer
    {
        public List primeList;

        public void findVersion(BigInteger goal)
        {
            BigInteger number = 3;
            primeList = new List { 2 };

            try
            {
                while (number < goal)
                {
                    if (isPrime(number))
                        primeList.Add(number);
                    number += 2;
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
            }
            finally
            {
                Console.WriteLine("i found " + primeList.Count + " Prime Numbers");
                Console.WriteLine(primeList.Last() + "was the last Prime");
            }
        }  

        private bool isPrime(BigInteger number)
        {
            foreach (BigInteger prime in primeList)
                if (number % prime == 0)
                    return false;

            return true;
        }
    }
}


You can call it like:

primer.findVersion1(999999);

Solution

Leaving aside the algorithm there are a number of points about the code

Naming

Pascal casing is standard for C# - SimplePrimer and FindVersion as opposed to simplePrimer and findVersion.

FindVersion seems unconnected to the functionality.

Structure

public fields are generally frowned upon. If it needs to be part of the interface, make it a Property so that the implementation can be changed if needed.

Having a separate 'return' as PrimeList seems overly complicated. There is no strong reason for not having List GetPrimes(BigInteger goal)

Looking at the code, I cannot see anything obvious that might throw an exception that might be caught by the catch (perhaps an out of range on the BigInteger?) Is it needed?

As a shape I would push for any output to be external to the function. Have the calling code catch errors or report results. It makes unit testing a lot simpler

Context

StackExchange Code Review Q#56480, answer score: 8

Revisions (0)

No revisions yet.