2016-09-10 3 views
1

Rubyでユークリッドのアルゴリズムを実装するための簡単な再帰的なメソッドに取り組んでいましたが、ベースケースに達すると希望の値を返す方法を見つけ出しました。Rubyでの再帰の振る舞い

def euclid_alg(larger,smaller) 
    if larger % smaller == 0 && smaller != 1 
    return smaller 
    else 
    puts 'calling self' 
    euclid_alg(smaller, (larger % smaller)) 
    puts 'executed section after call' 
    end 
    puts "made it here #{smaller} #{larger}" 
    nil 
end 
puts euclid_alg(100,15) 

そして出力:ここで私は遠くに持っているものだからの出力がない

calling self 
calling self 
executed section after call 
made it here 10 15 
executed section after call 
made it here 15 100 

注私は最大公約数を返すように期待していた「euclid_alg(100,15)を置きます」 100と15の5、

私はputs smallerと3行目のreturn smallerを交換しました。新しい出力は:

calling self 
calling self 
5 
made it here 5 10 
executed section after call 
made it here 10 15 
executed section after call 
made it here 15 100 

は、コンソール出力に「ここにそれを作った5 10」の追加がreturn文が関数呼び出しの抜け出しが、されていないことを明らかにし、「親のコール。」

どのようにして再帰を改善できますか?

+0

読者:[ウィキ(https://en.wikipedia.org/wiki/Euclidean_algorithm)から、ユークリッドアルゴリズム「は、2つの最大公約数(GCD)を計算するための効率的な方法であります残りの部分を残さずに両者を分ける最大の数字です」。 –

答えて

2

コードは問題ありません。あなたは単に返品がありません。注:

def euclid_alg(larger,smaller) 
    if larger % smaller == 0 && smaller != 1 
    return smaller 
    else 
    puts 'calling self' 
    return euclid_alg(smaller, (larger % smaller)) # <<<<< Return here 
    puts 'executed section after call' 
    end 
    puts "made it here #{smaller} #{larger}" 
    nil 
end 
puts euclid_alg(100,15)