Badges
Activity Feed
Created a new thread : Primes Calculation Optimization || C# Only!
Heres my code and time try making a faster one and ill try to beat it and remember c# only!
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Primesv1
{
internal class Program
{
static void Main()
{
const int limit = 1000000;
const int repetitions = 100;
long totalTicks = 0;
for (int i = 0; i < repetitions; i++)
{
Stopwatch sw = new Stopwatch();
sw.Start();
int primeCount = CountPrimes(limit);
sw.Stop();
totalTicks += sw.ElapsedTicks;
Console.WriteLine($"Iteration {i + 1}: Found {primeCount} prime numbers in {sw.ElapsedMilliseconds} ms");
}
double averageTimeMs = (double)totalTicks / Stopwatch.Frequency / repetitions * 1000;
Console.WriteLine($"\nAverage time for {repetitions} iterations: {averageTimeMs} ms");
}
static int CountPrimes(int n)
{
bool[] isPrime = new bool[n + 1];
for (int i = 2; i <= n; i++)
{
isPrime[i] = true;
}
for (int p = 2; p * p <= n; p++)
{
if (isPrime[p])
{
for (int i = p * p; i <= n; i += p)
{
isPrime[i] = false;
}
}
}
int count = 0;
for (int i = 2; i <= n; i++)
{
if (isPrime[i])
{
count++;
}
}
return count;
}
}
}
https://cdn.discordapp.com/attachments/1161846372551622688/1162389570554433606/image.png?ex=653bc2a5&is=65294da5&hm=b99cda85c974b0f84c673e7e2651213b9dfe1715b364cc3a8457039552d0fd68&