LoginSignup
4
3

More than 5 years have passed since last update.

コラッツ問題でRubyの練習

Posted at

コラッツ問題@Wikipedia

ある自然数n(0でない)に対して以下を繰り返す。
* 奇数だったら3倍して1足す
* 偶数だったら2で割る

例: 10 -> 5 -> 16 -> 8 -> 4 -> 2 -> 1

書いて計算すればなんてこと無いですが、暗算だといきなりエキサイティングです。
1〜2時間暇な時は「27」から始めるのがオススメ。

collaz.rb
def calc(x)
  if x.even? then
    x = x/2
  else
    x = (x*3)+1
  end
  puts sprintf("%10d", x)
  return x
end

x = ARGV[0].to_i
try = 0

puts "Start: #{x}"

while x != 1 do
  try += 1
  x = calc(x)
end

puts ".........."
puts "Steps: #{try}"

使い方:
ruby collaz.rb 27

4
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
3