From: "佐藤 大輔" Date: 2000-07-03T09:02:26+09:00 Subject: [ruby-list:23661] return とスタックの関係? 佐藤です。 チャチャにすぎません。お目汚しでごめんなさい。 ruby 1.4.5でKondara MNU/Linux版(Jirai)を使用しています。 pythonの練習をしてる最中に気付いたことです。 こんなスクリプトを書いてみました。 インチキしてますが、階乗を求めるfact()です。 # 数学では n<0の時のn!はどうなるんでしたっけ。 0!=1だったのは覚えてるけど #!/usr/bin/ruby def fact(x) return 1 if x == 1 return 1 if x < 1 return x * fact(x-1) end if __FILE__ == $0 ARGV.each do |n| print "#{n}: #{fact n.to_i}\n" end end 400の階乗なら行けるのですが、数字を増やすとスタック溢れでコケます。 その数は縁起の悪い666でした。 で、 def fact(x) return 1 if x <= 1 return x * fact(x-1) end も666まででしたが、 def fact(x) return 1 if x <= 1 x * fact(x-1) end だと901まででした。 def fact(x) if x == 1 1 elsif x < 1 1 else x * fact(x-1) end end だと918までいけましたが、面白いのが、 def fact(x) if x <= 1 1 else x * fact(x-1) end end だと901が限界だったこと。短いのに負けるのね。 glibcが2.1.90というのが一因かもしれないのですが、returnを使う、使わない でコスト的な違いが生じるのでしょうか。 某師匠の話では1.5系ではもっと増やせたという話です。また、Debian potateで は1.4.4でも800はいったという話です。 -- 我が生涯の一片に悔いなし!! by おれ 佐藤 大輔/densuke@ga2.so-net.ne.jp ふがほげにっき: http://www11.freeweb.ne.jp/diary/d-sato/diary/