Prime number calc.

The following code is my prime number calculator.

It makes 2 assumptions: 1 is always going to be assumed prime. 2 is always going to be assumed prime.

By making these two assumptions, you can seed the prime number pool with 2, and skip the foolishness of testing to see if the laws of math have changed.  By not seeding with 1, you don’t waste time testing for an always true condition of can it be divided by 1, and still not have a remainder. This is also a law of math that does not need to be tested.

So here is the code.

using System;
using System.Collections.Generic;
using System.Text;
 
namespace PrimeTest
{
    class Solution
    {
        static void Main(string[] args)
        {
            StringBuilder sb = new StringBuilder();
            sb.Append("1, ");
            sb.Append("2, ");
 
            List<decimal> primes = new List<decimal>();
            primes.Add(2); 
 
            for (decimal n = 3; n < 101; n++)
            {
                bool isNotPrime = false;
                foreach (decimal i in primes)
                {
                    decimal ret = n / i;
                    isNotPrime |=  (((int)ret) == ret);
                }
 
                if (!isNotPrime)
                {
                    sb.Append(string.Format("{0}, ", n));
                    primes.Add(n);
                }
            }
            Console.WriteLine(sb.ToString());
            Console.WriteLine("Finished - HIT A KEY");
            Console.ReadLine();
        }
    }
}

There is a bug, I found in higher numbers, non-prime starts sneaking.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.