I can see a few things you could do to speed up the code, although none of them seem to explain the sharp drop in performance you are experiencing. The most likely culprit, apparently, is the limitation of RAM, as suggested by Alexander Vogt.
The first thing you need to do is change the prime from integer to logical . This reduces memory requirements and also speeds up the evaluation of if (prime(a)==0) .
The relevant parts of the code are as follows
logical(1),allocatable:: prime(:) primeCount=0 allocate(prime(max)) prime = .false. prime(1)=.true. do a=2,int(sqrt(real(max))) !the main loop if(.not. prime(a))then !if the number is marked as prime procede do b=2*a,max,a !eliminate all the numbers that are multiples of the number if(.not. prime(b))then !but only spend time eliminating if the number is still marked prime prime(b)=.true. end if end do end if end do do a=1,max if(.not. prime(a))then primeCount=primeCount+1 end if end do
I am not programming Java, but in Matlab, if you declare prime(1:max)=0 , and then only change the values โโof bewteen 0 and 1 . I think Matlab treats the array as a logical array. Java can do the same. This may explain why your Java code does not suffer from performance degradation (assuming the RAM limitation is indeed a problem).
EDIT: I did some experiments.
On my machine (Debian Linux 64bit, i3, 16GB RAM, ifort 14 with default flags max=800 million (8E8) it took 22 seconds for max=800 million (8E8) . max=2E9 took 60 seconds. This is not the watch that was reported in the question. Also, in each case, the prime array was initialized to zero.
In addition, using integer(1) will run the program 33% faster than using integer(4) . With logical(1) it runs less than 5% faster than with integer(1) . This behavior is probably associated with better use of cash, since each prime element takes up less memory space, so the processor can perform more iterations when the data currently in cash goes through the cycles much faster.
The conclusions that I would like to draw from this would be that the culprit was the lack of RAM, as Alexander Vogt noted, and that there is a fair likelihood that the author's experience was not affected by the lack of initialization of the prime array (although that definitely should not have been happen) as HighPerformanceMark pointed out. Further, I suspect that Java declared prime as a logical array, and therefore the problem did not arise there. (Although 2 ^ 31 in 15 seconds in Java? The Fortran code used here doesn't come close to this. Was the same code mapped?)