Get the greatest common divisor

This efficient JavaScript function returns the greatest common divisor of a series of numbers.
  1. function GCD(nums)
  2. {
  3.  if(!nums.length)
  4.  return 0;
  5.  for(var r, a, i = nums.length – 1, GCDNum = nums[i]; i;)
  6.  for(a = nums[–i]; r = a % GCDNum; a = GCDNum, GCDNum = r);
  7.  return GCDNum;
  8. }
  9. alert(GCD([1284]))// Will return 4

Leave a Reply

Your email address will not be published. Required fields are marked *

Back To Top