计算斐波那契(Fibonacci)

2015-01-19 0 608
计算斐波那契(Fibonacci)
# Calculate the Fibonacci to 'x' number of places and return it as an array
def Fibonacci(limit)
  # Creates a new array
  array = Array.new
  # Our first number
  num1 = 1
  # Our second number
  num2 = 1
  # Our next number
  nextNum = 0
  # Loop through until we reach our limit
  # NOTE: we need to subtract 2 because we will add two numbers to the beginning later
  while nextNum < (limit - 2)
    # Our third number will be made by adding our first and second number together
    num3 = num1 + num2;
    # Our new first number is our old second number
    num1 = num2;
    # Our new second number is our old third number
    num2 = num3;
    # Insert our new number into our array
    array.insert(nextNum, num3)
    # This will be our next number
    nextNum += 1 # You can also use: nextNum = nextNum.next
    # Exit the 'while' loop
  end
  # Insert the number 1 into the beginning of our array
  array.insert(0, 1)
  # Insert the number 1 into the 2nd position of our array
  array.insert(1, 1)
  # Return our array
  return array
  # Exit the method
end

遇见资源网 ruby 计算斐波那契(Fibonacci) http://www.ox520.com/16228.html

常见问题

相关文章

发表评论
暂无评论
官方客服团队

为您解决烦忧 - 24小时在线 专业服务