Skip to content

Latest commit

 

History

History
32 lines (23 loc) · 1.14 KB

2008-09-19-new-gem-greatest_common_factor.textile

File metadata and controls

32 lines (23 loc) · 1.14 KB
layout title
post
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:

{% highlight ruby }
[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]
{
endhighlight %}

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).

{% highlight ruby %}
[12,16,8,41].greatest_common_factor => nil

  1. 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

{% endhighlight %}

Enjoy!