Skip to content

Instantly share code, notes, and snippets.

@Marak
Last active October 12, 2015 03:58
Show Gist options
  • Save Marak/3967740 to your computer and use it in GitHub Desktop.
Save Marak/3967740 to your computer and use it in GitHub Desktop.
Experimenting with new process.prevTick() API
//
// 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