昨日に引き続きIntegerに関して。 個人的に、Integerブームが起こってます。

Integerに関しては、http://www.ruby-doc.orgのClass: Integerを参照のこと。

今日は最大公約数と最小公倍数を同時に返してくれるInteger#gcdlcmについてです。

このInteger#gcdlcmの実装が気に入らない!!

どこが気に入らないのかという本題に入る前に、Integer#lcmについての実装を見てみよう!

   1  # File lib/rational.rb, line 457
   2    def lcm(other)
   3      if self.zero? or other.zero?
   4        0
   5      else
   6        (self.div(self.gcd(other)) * other).abs
   7      end
   8    end

オーソドックスなの最小公倍数の求め方。 ここではあまり問題にしない。

このコードをよーく覚えておいてください。

ここからが本題です。

Integer#gcdlcmの実装を見て見る。

   1  # File lib/rational.rb, line 473
   2    def gcdlcm(other)
   3      gcd = self.gcd(other)
   4      if self.zero? or other.zero?
   5        [gcd, 0]
   6      else
   7        [gcd, (self.div(gcd) * other).abs]
   8      end
   9    end

Integer#lcmにそっくり!

・・・って、Integer#lcmのコードにInteger#gcdいれただけじゃないですか・・・。

せっかくこのコードの直前で、Integer#lcmを定義してるのに、何で使わないんやろうか・・・。

   1  def gcdlcm(other)
   2    return [self.gcd(other), self.lcm(other)]
   3  end

という風に書いても不都合はなさそうやけど・・?

むしろ、こういう風に書いてくれたほうが、気持ちいいんやけども。

ん~、Integerには謎がいっぱいや。

posted by Png y_tsuda on Fri 15 Aug 2008 at 04:06
Contents
Integer#gcdlcmの実装が気に入らない
Comments
瀧内元気: MacOS版は以下にあります * [genki/ViMouse](https://githu... '23-1
KingofSmack: Here also good reads for this mobile applicatio... '14-5
Spencer: You don't have to re-compile it, this version w... '14-4
staiano: Any chance we can get a recompile for 10.9? '14-1
dsjf: https://gist.github.com/6bf1bf2c3cbb5eb6e7a7 これ... '13-1
Services from s21g
twpro(ツイプロ)
Twitterプロフィールを快適検索
地価2009
土地の値段を調べてみよう
MyRestaurant
自分だけのレストラン手帳
Formula
ブログに数式を埋め込める数式コミュニティ