An Expanded and Streamlined Euclidean Algorithm for Computing the Greatest Common Divisor.
This method for using the Euclidean Algorithm to compute the Greatest Common Divisor will accept any quantity of integers whose values are greater than zero and not equal to each other.
by Vinyasi
HTML
<div align="center">
<h1 id="demonstration"></h1>
</div>
JavaScript
// Find the GCD of these four integers...
// Replace with as many as you like...
var ofTheseIntegers = [30, 100, 25, 75];
// Invoke the function...
var firstPart = 'The Greatest Common Divisor<br />of these four integers:<br />' + ofTheseIntegers[0] + ', ' + ofTheseIntegers[1] + ', ';
var secondPart = ofTheseIntegers[2] + ' and ' + ofTheseIntegers[3] + ' is <span style="color:red"><big>' + getTheGCD(ofTheseIntegers) + '</big></span>';
document.getElementById("demonstration").innerHTML = firstPart + secondPart;
var terms = [];
function getTheGCD(terms) {
var q; // for debugging
var i; // for incrementing conditional 'for' loops
var v; // for incrementing conditional 'for' loops
// Quantity of integers whose GCD is to be sought...
var count = terms.length;
// Last position of an integer within 'terms'...
var last = count - 1;
// Sort the contents of 'terms'...
terms.sort(function(a, b) {
return a - b;
});
// This has to be at least one greater than the largest integer in the array: 'terms'.
// Otherwise, the sort function will push all the numbers to the top of the 'terms' array
// and begin to cut them out a little at a time!
var numeric_padding = terms[last] + 1;
// Permanently save the quantity of integers...
var save_count = count;
// Temporarily save the quantity of integers...
var kount = count;
// Establish a second array, 'remains', to swap with the contents of 'terms' and
// continue to swap them back and forth to each other throughout the 'while' loop below...
var remains = [];
remains[0] = 0;
// Perform our first "shift to the right" of the contents of 'terms'...
for (i = 0; i < (count - 1); i++) {
remains[i + 1] = terms[i];
}
// Uncomment the following line for debugging...
//for (q = 0; q < 4; q++)
// ...and comment out the next line for debugging...
while (kount > 1) {
// Transfer 'count' to 'kount' since neither variable will retain
// their values throughout the...