计算斐波那契(Fibonacci)
- 作者: 简简单单单
- 来源: 51数据库
- 2022-08-12
# 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
推荐阅读