# 计算斐波那契（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
#该片段来自于http://outofmemory.cn

0人收藏

0

0

»更多 您可能感兴趣的代码
1. 2014-07-05 12:44:14Ruby mergesort 归并排序 by digua
2. 2014-08-18 12:05:26Ruby 冒泡排序 by Ω油菜
3. 2014-10-08 09:26:56Ruby：最大公因数/最小公倍数 by digua
4. 2014-05-24 13:36:45Fibonacci series 斐波纳契数列 by digua
5. 2014-08-27 12:54:24Ruby快速排序法 by 永明
6. 2014-10-19 10:31:39工资税率算法 by 好好学习啊
7. 2014-05-24 14:12:41Ruby 冒泡排序 by LeoSun
8. 2014-11-16 13:55:51费马素性检验 by jeffsui
9. 2014-10-16 09:55:26ruby 打印杨辉三角型代码 by 永明
10. 2014-07-22 12:01:50Ruby：简单的插入排序 by 永明
11. 2012-11-25 10:56:14ruby实现二分查找算法 by 二糊