Code below works for stated number (6008514751), but throws up error for the desired Max value: 600851475143. I've used type long in place of 'int', so I don't see why my program is not able to run 600851475143. I would greatly appreciate any help.
Error thrown is:
Unhandled Exception:
System.OverflowException: Arithmetic operation resulted in an overflow.
at HelloWorld.MakeSieve (System.Int64 max) [0x00000] in <0273ea83c32446be9aa2f9fc5d30dab0>:0
at HelloWorld.Main () [0x00000] in <0273ea83c32446be9aa2f9fc5d30dab0>:0
[ERROR] FATAL UNHANDLED EXCEPTION: System.OverflowException: Arithmetic operation resulted in an overflow.
at HelloWorld.MakeSieve (System.Int64 max) [0x00000] in <0273ea83c32446be9aa2f9fc5d30dab0>:0
at HelloWorld.Main () [0x00000] in <0273ea83c32446be9aa2f9fc5d30dab0>:0
*Update 1: Some of you suggested I take a look at "I need very big array length(size) in C#". I tried replacing my list with type double (even tried replacing all 'long' with 'double), to no avail.
Update 2: A trailing L (Max = 600851475143L) not helping much.
Thank you!
using System;
using System.Collections.Generic;
class HelloWorld
{
public static long Max = 600851475;
public static List<long> AllPrimesBelowMax = new List<long>();
public static long maxPrime = 0;
static void Main()
{
MakeSieve(Max);
}
private static bool[] MakeSieve(long max)
{
bool[] isPrime = new bool[max + 1];
for (long i = 2; i <= max; i++)
{
isPrime[i] = true;
}
//cross out multiples
for (long i = 2; i <= max; i++)
{
//check if i is prime
if (isPrime[i] == true)
{
//cross out multiples of i
for (long j = i * 2; j <= max; j += i)
{
isPrime[j] = false;
}
}
}
for (long i = 2; i <= max; i++)
{
if (isPrime[i] == true)
{
AllPrimesBelowMax.Add(i);
}
}
Console.WriteLine(AllPrimesBelowMax[AllPrimesBelowMax.Count - 1]);
return isPrime;
}
}