返回顶部

收藏

计算斐波那契(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

标签:ruby,算法

收藏

0人收藏

支持

0

反对

0

»更多 您可能感兴趣的代码
  1. 2014-05-23 21:21:29Ruby合数 by jeffsui
  2. 2014-07-05 12:44:14Ruby mergesort 归并排序 by digua
  3. 2014-08-18 12:05:26Ruby 冒泡排序 by Ω油菜
  4. 2014-10-08 09:26:56Ruby:最大公因数/最小公倍数 by digua
  5. 2014-05-24 13:36:45Fibonacci series 斐波纳契数列 by digua
  6. 2014-08-27 12:54:24Ruby快速排序法 by 永明
  7. 2014-10-19 10:31:39工资税率算法 by 好好学习啊
  8. 2014-05-24 14:12:41Ruby 冒泡排序 by LeoSun
  9. 2014-11-16 13:55:51费马素性检验 by jeffsui
  10. 2014-10-16 09:55:26ruby 打印杨辉三角型代码 by 永明
  11. 2018-03-30 21:56:50java自动识别用户上传的文本文件编码 by Hugh
相关聚客文章
  1. 0X55AA 发表 2014-08-04 05:23:46 ruby交互模式工具pry
  2. 0X55AA 发表 2014-08-04 05:23:46 ruby交互模式工具pry
  3. 博主 发表 2012-12-20 02:45:00 最全的 Ruby/ Rails 保留字 ( ruby/rails reserved words co
  4. 博主 发表 2014-10-07 11:17:00 ruby v.s. object-c
  5. 博主 发表 2015-06-28 00:56:00 如何打印ruby的动态代码
  6. 蘅芜散人 发表 2015-07-10 17:17:54 Rotate List
  7. 博主 发表 2015-06-29 07:23:14 Blog迁移到Hexo
  8. Optimus Prime 发表 2015-07-28 01:46:30 论证:为什么大数据是下一个浪潮?
  9. linux@linux.cn (linu 发表 2015-08-13 07:10:00 Ruby Web 服务器这十五年
  10. Big data 发表 2015-08-03 12:23:36 算法可以帮风险投资家做出更好的投资决策吗?
  11. 比特币 发表 2015-08-20 14:56:38 算法、技术及其它
  12. rainy 发表 2015-09-02 15:52:26 网页正文及内容图片提取算法

发表评论