I have just started learning C# and decided to do some problems from Project Euler. I wrote a code to find 10 001st prime and I thought it would be cool optimize it to make it as fast as possible. How could I improve this to make it even faster?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Diagnostics;
namespace primes
{
class Program
{
static void Main(string[] args)
{
long prime = 2;
long largestprime = 2;
long potentialprime = 3;
Console.WriteLine("Enter the prime you want to find: ");
long primenum = Convert.ToInt64(Console.ReadLine());
long[] primearray = new long[primenum + 1];
primearray[1] = 2;
Stopwatch sw = new Stopwatch();
sw.Start();
while (prime <= primenum)
{
bool isprime = true;
for (long x = 1; x < prime; x += 3)
{
if (primearray[x] * primearray[x] > potentialprime)
break;
if (prime > 3 && (potentialprime % primearray[x] == 0 || potentialprime % primearray[x+1] == 0 || potentialprime % primearray[x+2] == 0))
isprime = false;
if (prime <= 3 && potentialprime % primearray[x] == 0)
isprime = false;
}
if (isprime)
{
primearray[prime] = potentialprime;
prime += 1;
largestprime = potentialprime;
}
potentialprime += 2;
}
sw.Stop();
Console.WriteLine(sw.ElapsedMilliseconds + "ms to find ");
Console.WriteLine(largestprime);
Console.ReadKey();
}
}
}