Greatest common divisor: Difference between revisions
Content deleted Content added
→{{header|PowerShell}}: port short Python implementation |
|||
Line 1,375: | Line 1,375: | ||
=={{header|JavaScript}}== |
=={{header|JavaScript}}== |
||
Iterative |
Iterative implementation |
||
<lang javascript>function gcd(a,b) { |
<lang javascript>function gcd(a,b) { |
||
a = Math.abs(a); |
|||
b = Math.abs(b); |
|||
⚫ | |||
if (b > a) { |
|||
var temp = a; |
|||
a = b; |
|||
b = temp; |
|||
⚫ | |||
⚫ | |||
⚫ | |||
⚫ | |||
⚫ | |||
if (a === 0) { return b; } |
|||
⚫ | |||
⚫ | |||
⚫ | |||
}</lang> |
}</lang> |
||
Recursive. |
Recursive. |
||
<lang javascript>function gcd_rec(a, b) { |
<lang javascript>function gcd_rec(a, b) { |
||
⚫ | |||
⚫ | |||
return gcd_rec(b, a % b); |
|||
⚫ | |||
⚫ | |||
⚫ | |||
}</lang> |
}</lang> |
||
Implementation that works on an array of integers. |
|||
<lang javascript>function GCD( |
<lang javascript>function GCD(arr) { |
||
var i, y, |
|||
n = arr.length, |
|||
x = Math.abs(arr[0]); |
|||
{ var y = A[i] < 0 ? -A[i] : A[i]; |
|||
for (i = 1; i < n; i++) { |
|||
y = Math.abs(arr[i]); |
|||
⚫ | |||
while (x && y) { |
|||
⚫ | |||
} |
|||
x += y; |
|||
} |
|||
return x; |
|||
} |
} |
||
/ |
//For example: |
||
GCD([57,0,-45,-18,90,447]); //=> 3 |
|||
</lang> |
|||
=={{header|Joy}}== |
=={{header|Joy}}== |