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?
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();
}
}
}
this brings us to 25999,5974ms for the calculation of the first 1.000.000 primes
. Your code does not reflect that statement. It does not find the first 1 million primes. Rather it finds all the primes up to 1 million. Using a sieve would take less than 6ms running in 64 bit Release mode. \$\endgroup\$