It fails at Values.Capacity = n; Previously Values was just an array defined like this : bool[] Values = new bool[n]; but had the same result. I am passing primesieve an int.MaxValue.
static int[] Primesieve(int n)
{
List<bool> Values = new List<bool>();
Values.Capacity = n;
int[] primes = new int[(int)Math.Sqrt(n)];
int primecount = 0;
Values[0] = true;
Values[1] = true;
for (int i = 0; i < Math.Sqrt(n); i++)
{
if (Values[i] == false)
{
for (int j = i * i; j < Values.Count; j += i)
Values[j] = true;
primes[primecount] = i;
primecount++;
}
}
return primes;
}
I believed my problem to be that since they are bools, a value type they are being created on the stack so I did this to force heap allocation. but it still fails at the same place.
public class Reference<T>
{
public T Ref;
}
static int[] Primesieve(int n)
{
List<Reference<bool>> Values = new List<Reference<bool>>();
Values.Capacity = n;
int[] primes = new int[(int)Math.Sqrt(n)];
int primecount = 0;
Values[0].Ref = true;
Values[1].Ref = true;
for (int i = 0; i < Math.Sqrt(n); i++)
{
if (Values[i].Ref == false)
{
for (int j = i * i; j < Values.Count; j += i)
Values[j].Ref = true;
primes[primecount] = i;
primecount++;
}
}
return primes;
}
My machine has 16gb of ram running win7 64-bit and i even targeted the build specifically to x64. So I know it cat actually be running out of memory as int.MaxValue Booleans should only take around 2gb assuming .Net is not packing 8 of them into 1 byte, and if it is then it should only really take up 265mb.Or am I some how still failing to use the heap?