Greatest common divisor (gcd) of two integers HTML5

Greatest common divisor (gcd) of two integers HTML5


Greatest common divisor (gcd) of two integers HTML5
http://iwant2study.org/ospsg/index.php/812
http://www.iwant2study.org/lookangejss/math/ejss_model_GreaterCommonDivisor/

Math

If two numbers, m and n are given, the greatest common divisor of m and n, denoted by gcd(x,y) can be found by reducing the numbers to smaller numbers using the following mathematics results

gcd(x,y) = gcd(y,x%y).
Hence, gcd(34, 8) = gcd(8, 2) = gcd(2,0) = 2


Code

function gcd_two_numbers(x, y) { //using 34,8 as example
if ((typeof x !== 'number') || (typeof y !== 'number'))
return false;
x = Math.abs(x);
y = Math.abs(y);
while(y>0) { // do this while y is greater than 0, in other words remainder of x%y is non-zero
var t = y; //dummy t variable
y = x % y; // 34%8 assign y =2 y= 8%2 = 0 y =2 y =0

x = t; // assign t back to x x=2 x=8 x= 2
}
return x; // return as output when the algorithm stops


}
Next Post Previous Post
No Comment
Add Comment
comment url