Reputation: 3537
I developed the Eratosthene's Sieve algorithm in C and Java, but I encountered some problems.
To manage the array of prime numbers I used an array of char for C (8 bit for each element) and an array of boolean for Java (8 bit for each element).
When I try to calculate the prime numbers until N=1,000,000,000 (so there is an array of N elements), the Java application works great (I expanded the heap size to 1,5GB). When I try to do the same with the C application it runs out of memory (the limit is N=680,000,000).
When I run both the applications with the same N=500,000,000 I checked and both occupy about 512MB of RAM, so if the Java application works fine with N=1,000,000,000 I don't understand why the C application fails to run immediately.
Is there an "option" for C like the "-Xmx1536m" of Java that I don't know?
I have 4GB of RAM and I use Windows 7 64bit. I also checked the sizeof(size_t) value and it is 32, so I guess I can rightly allocate 4GB of memory.
EDIT: I tried the 64bit version of Cygwin and now it works fine with N=1,000,000,000. Is there a reason for this? I guess 1GB of memory "requires" 32bit, not 64...
Here there are the applications' sources.
Java:
int N = 1000000000;
int m;
boolean[] isPrime = new boolean[N + 1];
for (int i = 2; i <= N; i++) {
isPrime[i] = true;
}
for (int i = 2; i*i <= N; i++) {
if (isPrime[i]) {
for (int j = i; (m = i*j) <= N; j++) {
isPrime[m] = false;
}
}
}
C:
int N = 1000000000;
int i, j, m;
char *isPrime;
isPrime = malloc(sizeof(char)*(N+1));
for (i = 2; i <= N; i++) {
isPrime[i] = 1;
}
for (i = 2; i*i <= N; i++) {
if (isPrime[i]) {
for (j = i; (m = i*j) <= N; j++) {
isPrime[m] = 0;
}
}
}
Upvotes: 4
Views: 337
Reputation: 135
This could be because of how memory allocation differs between the C runtime and the JVM. The C runtime guarantees a contiguous block of memory for array allowing you to do pointer arithmetic to access array elements. There are no such guarantees in Java which perhaps allows larger arrays to be allocated.
Upvotes: 1