I tried (on my Lubuntu Box) the following programs:
import java.util.*;
class Primes
{
static java.util.ArrayList<Integer> primos;
static boolean comprobarPrimacidad(int n)
{
Iterator<Integer> it = primos.iterator();
boolean primo = true;
do
{
if((n%it.next()) == 0) primo = false;
} while((primo == true) && (it.hasNext()));
if(primo) primos.add(n);
return primo;
}
public static void main( String [] args)
{
primos = new java.util.ArrayList<Integer>();
int n=2;
primos.add(n);
while ( primos.size() < 50000)
{
++n;
comprobarPrimacidad(n);
}
}
}
#include <vector>
using namespace std;
vector <unsigned int> primos;
bool calcularPrimalidad(unsigned int numero) {
bool primo = true;
vector<unsigned int>::iterator it = primos.begin();
do {
if ((numero % *it) == 0) primo = false;
it++;
} while (primo == true && it != primos.end());
if (primo == false) return false;
primos.push_back(numero);
return true;
}
int main()
{
unsigned int n=2;
primos.push_back(n);
while ( primos.size() < 50000)
{
++n;
calcularPrimalidad(n);
}
}
with the following execution times:
Java 0m8.573s
C++ 0m25.919s
C++ -O3 0m4.416s
Compiler optimization (
-O3 for g++
) apparently plays a major role.