emphatic solutions : ephemeral musings in the ether...
Brian Doll, Software/Systems Architect, San Francisco Bay Area, California

New gem – greatest_common_factor

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.

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!


Brian Doll is a husband, father, thought worker, tree-hugging, music-loving, punk, atheist, non-conformist, optimist, Quality seeker. Here you'll find a mix of thoughts on fitness (Crossfit, Paleo foods), philosophy and programming (Ruby, Rails and other goodies).


Generated by Jekyll
Copyright © 2007-2010 Brian Doll