当前位置:网站首页>Kotlin算法入门兔子数量优化及拓展
Kotlin算法入门兔子数量优化及拓展
2022-08-11 08:01:00 【易庞宙】
/* 古典问题:3个月起每个月都生一对兔子,小兔子长到第三个月后每个月又生一对兔子,假如兔子都不死,问每个月的兔子总数为多少? 分析:首先我们要明白题目的意思指的是每个月的兔子总对数;假设将兔子分为小中大三种,兔子从出生后三个月后每个月就会生出一对兔子, 那么我们假定第一个月的兔子为小兔子,第二个月为中兔子,第三个月之后就为大兔子,那么第一个月分别有1、0、0,第二个月分别为0、1、0, 第三个月分别为1、0、1,第四个月分别为,1、1、1,第五个月分别为2、1、2,第六个月分别为3、2、3,第七个月分别为5、3、5…… 兔子总数分别为:1、1、2、3、5、8、13…… 于是得出了一个规律,从第三个月起,后面的兔子总数都等于前面两个月的兔子总数之和,即为斐波那契数列。*/ class RabbitNumber { private var rabbits: Long = 1 private var lastSecondRabbits: Long = 0 private var lastRabbits: Long = 0 /** * 遍历从第一个月到第n个月的兔子总数 */ fun forEachMothsToRabbits(moths: Int) { println(System.currentTimeMillis()) for (i in 1..moths) println("第" + i + "个月兔子数为" + getRabbits(i)) println(System.currentTimeMillis()) } /** * 获取当前月的兔子总数 */ private fun getRabbits(moths: Int): Long { if (moths == 1 || moths == 2) return rabbits = 1 else if (moths == 3) return rabbits = 2 else { //初始化上一个月以及上两个月兔子数量 if (lastRabbits == 0L && lastSecondRabbits == 0L) { lastSecondRabbits = getRabbits(moths - 2) lastRabbits = getRabbits(moths - 1) } //计算这一个返回的兔子数量 rabbits = lastRabbits + lastSecondRabbits /*让两个月的兔子数等于上一个月兔子数,让上个月等于这个月兔子数 为了下一次计算(下月兔子数)更加高效快捷避免过冗余递归影响计算速率*/ lastSecondRabbits = lastRabbits lastRabbits = rabbits return rabbits } } }
边栏推荐
- 囍楽cloud task source code
- 欢迎加入sumarua网络安全交流社区
- Keep track of your monthly income and expenses through bookkeeping
- tf.cast(), reduce_min(), reduce_max()
- 1051 复数乘法 (15 分)
- 用 Antlr 重构脚本解释器
- 1.2 - error sources
- 2.1-梯度下降
- klayout--导出版图为gds文件
- go-grpc TSL authentication solution transport: authentication handshake failed: x509 certificate relies on ... ...
猜你喜欢
1046 punches (15 points)
1051 Multiplication of Complex Numbers (15 points)
TF generates (feature, label) set through feature and label, tf.data.Dataset.from_tensor_slices
3.1-Classification-probabilistic generative model
通过记账,了解当月收支情况
1036 Programming with Obama (15 points)
用 Antlr 重构脚本解释器
装饰器模式:Swift 实现
【LeetCode】链表题解汇总
4.1 - Support Vector Machines
随机推荐
Conditional statements in TF; where()
C Primer Plus(6) 中文版 第1章 初识C语言 1.6 语言标准
C语言-结构体
1106 2019 Sequence (15 points)
老干妈创始人陶华碧现身直播间,70岁“国民女神”拥抱直播电商
小目标检测3_注意力机制_Self-Attention
There may be fields that cannot be serialized in the abnormal object of cdc and sqlserver. Is there anyone who can understand it? Help me to answer
XXL-JOB 分布式任务调度中心搭建
基于微信小程序的租房小程序
tf.cast(), reduce_min(), reduce_max()
几何EX3 功夫牛宣布停售,入门级纯电产品为何总成弃子
oracle数据库中列转行,列会有变化
The most complete documentation on Excel's implementation of grouped summation
囍楽cloud task source code
机器学习(二)线性回归
3.1-分类-概率生成模型
查找最新人员工资和上上次人员工资的变动情况
【415. 字符串相加】
Serverless + domain name can also build a personal blog? Really, and soon
jenkins简单使用