Skip to main content
5 of 6
Rollback to Revision 3

Calculating primes until a user-given value

I am new to C# programming. I wrote a little program in C# to calculate all primes until a user-given value. Ignoring the lack of computing power I wrote this program to handle theoretically very huge numbers.

The code works properly. I have no error handling simply because it is a little program for myself. But I'd like some suggestions about error handling. :)

Can you give me suggestions to improve the code? Maybe even to make it faster?

Here's the code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.IO;

namespace ConsolePrimes
{
    public static class Program
    {
        public static void Main(string[] args)
        {
            Console.WriteLine("Up to which number shall all primes be calculated?");
            string inputvar = Console.ReadLine();
            ulong inputnumber = Convert.ToUInt64(inputvar);
            var primes = new List<ulong>();
            primes.Add(2);
            primes.Add(3);
            bool isprime = false;
            double result = 0;
            for (ulong i = 4; i<inputnumber; i++)
            {
                isprime = true;
                foreach (ulong prime in primes)
                {
                    result = i % prime;
                    if (result == 0)
                    {
                        isprime = false;
                        break;
                    }
                }
                if (isprime == true)
                {
                    primes.Add(i);
                }
            }
            int numberofprimes = primes.Count;
            Console.WriteLine("The Range from 0 to " + inputvar + " has " + Convert.ToString(numberofprimes) + " primes.");
            Console.WriteLine("The list of all primes is now getting exported to \"primes.txt\".");
            TextWriter tw = new StreamWriter("primes.txt");
            foreach (ulong nr in primes)
            {
               tw.WriteLine(nr);
            }
            tw.Close();
            Console.ReadLine();
        }
    }
}
Kajkrow
  • 213
  • 1
  • 6