Last active
October 12, 2015 03:58
-
-
Save Marak/3967740 to your computer and use it in GitHub Desktop.
Experimenting with new process.prevTick() API
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// Calculating prime factors in polynomial time using node.js process.prevTick() | |
// | |
// see: http://en.wikipedia.org/wiki/Prime_factor | |
// see: http://en.wikipedia.org/wiki/Novikov_self-consistency_principle | |
// | |
// Authors: | |
// http://jesusabdullah.net/ | |
// http://marak.com | |
// | |
function primeFactor (n) { | |
// | |
// If f is not defined, initialize it to zero | |
// | |
if(typeof f === "undefined") { | |
var f = 0; | |
} | |
// | |
// 0 and 1 do not have prime factors | |
// | |
if(n === 0 || n === 1) { | |
return ('no prime factors found'); | |
} | |
// | |
// Check if f is a prime factor | |
// | |
if(f !== n && (f % n === 0) && isPrime(f)) { | |
// | |
// If f is a prime factor, send f to the previous tick | |
// | |
process.prevTick(function(){ | |
// | |
// Important: Must set correct value to f so the previous tick contains the solution | |
// | |
f = f; | |
}); | |
return f; | |
} else { | |
// | |
// If f is not a prime factor, send f+1 to the previous tick | |
// | |
process.prevTick(function(){ | |
f = f + 1; | |
}); | |
} | |
} | |
console.log(primeFactor(25)); // returns 5 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment