Skip to content

Commit

Permalink
crivo de Eratostenes
Browse files Browse the repository at this point in the history
  • Loading branch information
vigusmao committed Apr 5, 2021
1 parent bca759c commit 886646c
Showing 1 changed file with 58 additions and 22 deletions.
80 changes: 58 additions & 22 deletions Primos/src/Primos.java
Expand Up @@ -44,35 +44,72 @@ private static boolean ehPrimo(int x) {
return true;
}



public static int[] obterPrimosViaCrivo(int n) {
// ToDo IMPLEMENT ME!!!
boolean[] candidatos = new boolean[n + 1]; // preciso ir até a posição n
// inicializados com (true: (candidato a) primo; false: não é mais candidato)

return null;
}
for (int i = 2; i <= n; i++) {
candidatos[i] = true;
}

public static void main(String[] args) {
int candidatoDaVez = 2;
int quadradoDoCandidatoDaVez = 4;
int contNaoPrimos = 1;

while (quadradoDoCandidatoDaVez <= n) {
if (candidatos[candidatoDaVez]) {
for (int i = quadradoDoCandidatoDaVez; i <= n; i += candidatoDaVez) {
if (candidatos[i]) {
candidatos[i] = false;
contNaoPrimos++;
}
}
}
candidatoDaVez++;
quadradoDoCandidatoDaVez = candidatoDaVez * candidatoDaVez;
}

for (int n = 1; n <= 20; n++) {
int contPrimos = n - contNaoPrimos;

long inicio = System.currentTimeMillis();
int[] primos = obterPrimos(n);
long duracao = System.currentTimeMillis() - inicio;
int[] primos = new int[contPrimos];
int contPrimosCopiados = 0;
for (int i = 2; i <= n; i++) {
if (candidatos[i]) {
primos[contPrimosCopiados++] = i;
}
}

System.out.printf("Há %d primos no intervalo [1, %d].\n",
primos.length, n);
return primos;
}

// Se quiséssemos imprimir o array na tela
public static void main(String[] args) {

for (int i = 0; i < primos.length; i++) {
int x = primos[i];
if (i < primos.length - 1) {
System.out.printf("%d, ", x);
} else {
System.out.printf("%d\n", x);
}
}
int n = 4_000_000;

long inicio = System.currentTimeMillis();
int[] primos = obterPrimos(n);
long duracao = System.currentTimeMillis() - inicio;
System.out.printf("Há %d primos no intervalo [1, %d].\n",
primos.length, n);
System.out.printf("Sem crivo: duração = %.3f\n", duracao / 1000f);

inicio = System.currentTimeMillis();
primos = obterPrimosViaCrivo(n);
duracao = System.currentTimeMillis() - inicio;
System.out.printf("Há %d primos no intervalo [1, %d].\n",
primos.length, n);
System.out.printf("Via crivo: duração = %.3f\n", duracao / 1000f);

// Se quiséssemos imprimir o array na tela

// for (int i = 0; i < primos.length; i++) {
// int x = primos[i];
// if (i < primos.length - 1) {
// System.out.printf("%d, ", x);
// } else {
// System.out.printf("%d\n", x);
// }
// }
//
// // ou...
// for (int x : primos) { // for each... (para cada elemento de "primos"...)
Expand All @@ -81,6 +118,5 @@ public static void main(String[] args) {
//
// // ou...
// System.out.println(Arrays.toString(primos));
}
}
}

0 comments on commit 886646c

Please sign in to comment.