Skip to content

Instantly share code, notes, and snippets.

@yngwie74
Created February 1, 2012 01:04
Show Gist options
  • Save yngwie74/1714307 to your computer and use it in GitHub Desktop.
Save yngwie74/1714307 to your computer and use it in GitHub Desktop.
Mi implementación del problema #7 del proyecto Euler en Javascript 1.7
/***
* Implementación del problema #7 del proyecto Euler (http://projecteuler.net/problem=7):
* By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can see
* that the 6th prime is 13. What is the 10,001st prime number?
*
* Requiere javascript 1.7
*
* https://gist.github.com/1714307
***/
var Euler07 = (function() {
function isPrime(n) {
if (n < 2)
return false;
else if (n == 2)
return true;
else if ((n % 2) == 0)
return false;
var max_candidate = parseInt(Math.sqrt(n)) + 1;
for (var i = 3; i < max_candidate; i += 2)
if ((n % i) == 0)
return false;
return true;
}
function allPrimes() {
yield 2;
for (var n = 3; ; n += 2) {
if (isPrime(n)) {
yield n;
}
}
}
function getNthPrime(n) {
var r = 0, p = allPrimes();
for (var i = 0; i < n; i++) {
r = p.next();
}
return r;
}
var module = {};
module.isPrime = isPrime;
module.getNthPrime = getNthPrime;
return module;
}());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment