Ruby没有递增数字

时间:2016-08-15 03:21:29

标签: ruby

我编写代码来查找Collat​​z猜想所需的操作数量。但是,我的操作变量似乎没有递增。

我的代码是:

puts "Please input a number"
number = gets.chomp
number = number.to_i
operations = 0
modulo = number % 2
while number =! 1
    if modulo == 0
        number = number / 2
        operations = operations + 1
    elsif modulo =! 0 && number =! 1
        number = number * 3
        number = number += 1
        operations = operations + 2
    else
        puts "Uh oh, something went wrong."
    end
end
puts "It took #{operations} operations!"

我在https://www.repl.it上运行此代码。

1 个答案:

答案 0 :(得分:2)

首先,它是elsif;不是elseif(我在您的问题中对此进行了编辑)。不平等的标志是!=;不是=!。但这有一些不同的含义。 (即:number =! 1表示number = !1

在第12行,number = number += 1是什么?我认为你的意思是number += 1number = number + 1

现在,代码有效。 :)

这是最终版本。

puts "Please input a number"
number = gets.chomp
number = number.to_i
operations = 0
modulo = number % 2
while number != 1
    if modulo == 0
        number = number / 2
        operations = operations + 1
    elsif modulo != 0 && number != 1
        number = number * 3
        number = number + 1
        operations = operations + 2
    else
        puts "Uh oh, something went wrong."
    end
end
puts "It took #{operations} operations!"

用法:

Please input a number
256
It took 8 operations!

使用函数的最佳解决方案:

def collatz(n)
    if n % 2 == 0
        return n / 2
    else
        return 3*n + 1
    end
end
def chainLength(num)
    count = 1
    while num > 1
        count += 1
        num = collatz(num)
    end
    return count
end

puts "Please input a number"
number = gets.chomp
number = number.to_i
operations = chainLength(number)
puts "It took #{operations} operations!"

如果您需要更高的性能,请阅读动态编程 memoization 技术。