Reputation: 37
So I'm making a simple program to find the largest common divider (lcd) between two numbers, using the Euclidean Algorithm (http://www.math.jacobs-university.de/timorin/PM/continued_fractions.pdf, on the second page) it's very simple. So here's the function I've created:
function largest_common_divider(num1, num2) {
var remainder;
var alpha = num1;
var beta = num2;
for (i = 0; i < 100; i++) {
/* we want to find an "n" such that
n * beta <= alpha < (n + 1) * beta
I initiated n at 1 so that I could use n = 0
as the end condition for my loop */
for (n = 1; n <= 0; n++) {
if (alpha > (n * beta)) {
//still didn't find the n
} else if (alpha == (n * beta)) {
//Hurray! our beta is the lcd
n = 0;
return beta;
} else {
// figure out the remainder
// and set n = 0 to terminate the loop
remainder = alpha - (n - 1) * beta;
n = 0;
}
}
//If we didn't find our lcd, than the previous beta
//become the new alpha (largest number) and the
//the remainder becomes the new beta (smaller number)
alpha = beta;
beta = remainder;
}
}
Note that, in this program I expect only positive integers and num1 > numb2 always.
So, to test this function I made this:
var a = 45; var b = 15;
var bloopidy = largest_common_divider(a,b);
console.log("The largest common divider between " + a + " and " + b + " is: " +
bloopidy);
expecting the result to be 15, but what I got is "undefined". I used all the little knowledge I have to debug this, but I couldn't! I need help guy, any is appreciated. Thank you!!
Upvotes: 0
Views: 32
Reputation: 85767
Your second for
loop never runs:
for (n = 1; n <= 0; n++)
1
is not <= 0
, so the condition is not true to begin with, so the loop never starts.
That means your code can be reduced to:
function largest_common_divider(num1, num2) {
var remainder;
var alpha = num1;
var beta = num2;
for (i = 0; i < 100; i++) {
alpha = beta;
beta = remainder;
}
}
This doesn't contain an explicit return
, so it returns undefined
implicitly.
Upvotes: 3