Skip to content

Instantly share code, notes, and snippets.

@neizod
Forked from 140bytes/LICENSE.txt
Created October 2, 2011 19:52
Show Gist options
  • Save neizod/1257856 to your computer and use it in GitHub Desktop.
Save neizod/1257856 to your computer and use it in GitHub Desktop.
GCD - recursive style, variable arguments.

GCD (Greatest Common Divisor)

121b. Find greatest common divisor using Euclid's recursion algorithm. The function can accept variable number of arguments.

How to Use

Invoke function using at least 1 argument.

Nth arg (number) ... The number to find gcd. note that arg = 0 are not acceptable

Older version

Just 36b for 2 arguments! thanks to @Prinzhorn and @tsaniel.

function g(a,b){return b?g(b,a%b):a}

Note: rollback de6a6a -> 932264 since its much longer and hard to debug.

function g() { // the gcd function.
var a=arguments, // the arguments.
b=a[0], // init 1st argument as b.
c=a[1]|0; // init 2nd argument as c. if argument does not exist, set it to zero.
if(!a[2]) // check if there are just 2 arguments.
return c?g(c,b%c):b; // the result of the gcd, euclid's recursion algorithm.
for(var i=1; // init counter.
i<a.length; // loop through all argument except the first one.
b=g(b,a[i++])); // calculate each pair of arguments for gcd.
return b // the result of the gcd, in case of more than 2 arguments.
}
function g(){var a=arguments,b=a[0],c=a[1]|0;if(!a[2])return c?g(c,b%c):b;for(var i=1;i<a.length;b=g(b,a[i++]));return b}
DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE
Version 2, December 2004
Copyright (C) 2011 Nattawut Phetmak <http://about.me/neizod>
Everyone is permitted to copy and distribute verbatim or modified
copies of this license document, and changing it is allowed as long
as the name is changed.
DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
0. You just DO WHAT THE FUCK YOU WANT TO.
{
"name": "gcd",
"description": "calculate greatest common divisor, recursive style, variable arguments.",
"keywords": [
"gcd",
"math",
"number",
"recursive"
]
}
<!DOCTYPE html>
<title>GCD</title>
<div>Expected value: <b>42, 4, 1, 3729</b></div>
<div>Actual value: <b id="ret"></b></div>
<script>
// write a small example that shows off the API for your example
// and tests it in one fell swoop.
var gcd = function g(){var a=arguments,b=a[0],c=a[1]|0;if(!a[2])return c?g(c,b%c):b;for(var i=1;i<a.length;b=g(b,a[i++]));return b}
document.getElementById( "ret" ).innerHTML = [gcd(42),
gcd(8, 12),
gcd(150,500,5053,2550,50200),
gcd(4075797, 5366031, 5440611, 2300793)];
</script>
@Prinzhorn
Copy link

"b==0" can be shortened to "!b" ;-)

@tsaniel
Copy link

tsaniel commented Oct 3, 2011

Changing the places also works
function g(a,b){return b?g(b,a%b):a}

@neizod
Copy link
Author

neizod commented Oct 3, 2011

@Prinzhorn @tsaniel oh thanks! i'm try to move on to next version.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment