Skip to content

Instantly share code, notes, and snippets.

@brunoperezm
Created August 6, 2012 02:30
Show Gist options
  • Save brunoperezm/3269260 to your computer and use it in GitHub Desktop.
Save brunoperezm/3269260 to your computer and use it in GitHub Desktop.
numeros primos optimizados
import java.util.Scanner;
public class principal {
public static void main(String args[]) {
Scanner input = new Scanner(System.in);
int maximo = input.nextInt();
int x;
int total_num_prims = 0;
long start = System.currentTimeMillis();
for (x = 2; x<maximo; x++) {
boolean es_primo = false;
if (x%10000==0) { System.out.printf("Voy por los %d/%d \n", x, maximo); }
for (int sub_x = 2; sub_x<x; sub_x++) {
boolean keep_going = true;
if (x%sub_x == 0) {
keep_going = false; // Encotramos que no es primo
}
else if (sub_x == x-1) { // Es el ultimo numero
es_primo = true;
}
if (!keep_going) {
break;
}
}
if (es_primo) {
total_num_prims++;
}
}
System.out.printf("Al %d hay %d numeros primos", maximo, total_num_prims);
long elapsedTimeMillis = System.currentTimeMillis()-start;
float elapsedTimeSec = elapsedTimeMillis/1000F;
System.out.println(elapsedTimeSec);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment