Ruby already provides the ability to find the greatest common factor (gcf) of two integers. What if we could determine the greatest common factor across a whole array of integers? Now we can. I've just released "greatest_common_factor on github.":http://github.com/briandoll/greatest_common_factor/tree/master Here is a sample of what you can do with it:
  [12,16,8,40].greatest_common_factor => 4
  [12,16,8,40].gcf => 4
  [12,16,8,40].factored_by_gcf => [3, 4, 2, 10]
*Update:* You can now also specify a tolerance for greatest common factor calculations. In many cases, you'll have data that is _so close_ to having a common factor, but not perfectly. Let's see how changing the tolerance can provide a greatest common factor that's close enough (or as close as you let it be, anyway).
  [12,16,8,41].greatest_common_factor => nil
  # but, if we add a tolerance of 1
  [12,16,8,41].greatest_common_factor(1) => 4

  [11,15,9,41].greatest_common_factor => nil
  [11,15,9,41].greatest_common_factor(1) => 2
Enjoy!


Discussion, links, and tweets

Follow me on Twitter for more musings from the ether.

© 2007-2023 Brian Doll