projectEuler3(600851475143);
var projectEuler3 = function (composite) {
var result = 2;
while(composite > 1)
{
if (composite % result)
{
result++
} else {
composite = composite / result;
console.log(result);
}
}
};
views:
637answers:
3EDIT: Turns out this question is designed to be a how to change an algorithm (in general) from iterative to recursive...not, as I assumed, how to get an answer to a particular problem.
This is for Project Euler! Project Euler is purely for your own benefit...if you're going to have someone else do the work for you, you could probably just look up the answer on google somewhere and type it in.
I can only guess you've decided that your program is correct, but that it is too slow, and you're hoping to speed it up. Making your function recursive won't help.
The site points out that if your program doesn't solve the question quickly, there's a better approach...try a different tact.
Hopefully in the spirit both of Project Euler (learn-by-doing) and SO (learn-by-asking), here's a fairly generic template for making a loop into tail-call recursion:
var projectEuler3 = function(n) {
var pE3_inner = function(n, i) {
// magic happens here
// if neither n nor i has changed, this is an
// infinite recursion (and usually a stack overflow)
pE3_inner(n, i);
}
pE3_inner(n, 2);
}
Structure and Interpretation of Computer Programs introduces the difference between iterative and recursive algorithms, how to identify which is which (in some languages it's not so obvious!), and how to convert from one to the other.
In addition to being an excellent textbook.