Skip to content

Instantly share code, notes, and snippets.

@benek
Created January 13, 2012 04:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save benek/1604716 to your computer and use it in GitHub Desktop.
Save benek/1604716 to your computer and use it in GitHub Desktop.
Coding Kata 1
package codingdojo.numerosprimos;
/**
* @author benek
* Date: 12/01/12
* Time: 20:57
* www.javamexico.org
*/
public class NumerosPrimos {
public static void main(String args[]){
long inicio = System.currentTimeMillis();
int i = 2;
int primo = 0;
for (;;){
if (esPrimo(i)){
primo++;
}
if (primo == 10001){
break;
}
i++;
}
System.out.println(i);
long termino = System.currentTimeMillis();
System.out.println(termino - inicio);
}
private static boolean esPrimo(int numero){
if (numero == 2 || numero == 3){
return true;
} else {
for (int i = 2; i <= (int) Math.sqrt(numero); i++){
if (numero%i == 0){
return false;
}
}
return true;
}
}
}
@chochos
Copy link

chochos commented Jan 13, 2012

Este es el problema 7 de Project Euler.

nomás por mamonear, ahí te va en Scala:

def esPrimo(x:Int) = !(3 to scala.math.sqrt(x).toInt by 2 find { x%_==0 } isDefined)
def nextPrime(x:Int) = (x+2 to Int.MaxValue by 2 find esPrimo).get
def primo(x:Int) = (3/:(2 until x)) { (p,i) => nextPrime(p) }
primo(10001)

@benek
Copy link
Author

benek commented Jan 13, 2012

¡Está bastante chido! Con rangos, la combinación de 'to' y 'by' es muy útil, bastante optimizado.

Me gustó mi solución porque el primer intento (que de hecho fue el que quedó en la grabación) no me salió nada optimizado, tardaba más de 2000 ms, y con este ya solamente poco más de 20 ms.

@chochos
Copy link

chochos commented Jan 13, 2012

Por performance no hay bronca con ese código en Scala, no lo he medido pero el resultado sale en un intervalo de tiempo conocido por los programadores como "luego luego" (aproximadamente medio segundo o menos). Obvio no lo hice pensando en optimizar; estos ejercicios de PE me han servido mucho para aprender Scala, sobre todo las colecciones y todas sus bondades.

@benek
Copy link
Author

benek commented Jan 13, 2012

Yo sí ya lo medí aquí en local y efectivamente sale en el intervalo que mencionas "luego luego" aka "en chinga".

@neodevelop
Copy link

Deberías de ir al siguiente Dojo ese Chochos :D...

@chochos
Copy link

chochos commented Jan 13, 2012

Sí, pues a ver si al próximo...

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment