当前位置:网站首页>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 } } }
边栏推荐
猜你喜欢

Keep track of your monthly income and expenses through bookkeeping

如何通过开源数据库管理工具 DBeaver 连接 TDengine

关于#sql#的问题:怎么将下面的数据按逗号分隔成多行,以列的形式展示出来
3.1-分类-概率生成模型

Write a resume like this, easy to get the interviewer

查找最新人员工资和上上次人员工资的变动情况

支持各种文件快速重命名最简单的小技巧

无服务器+域名也能搭建个人博客?真的,而且很快

Active users of mobile banking grew rapidly in June, hitting a half-year high

Serverless + domain name can also build a personal blog? Really, and soon
随机推荐
1071 Small Gamble (15 points)
Use tf.argmax in Tensorflow to return the index of the maximum value of the tensor along the specified dimension
零基础SQL教程: 基础查询 05
Break pad source code compilation--refer to the summary of the big blogger
Do you know the basic process and use case design method of interface testing?
2022-08-10 mysql/stonedb-slow SQL-Q16-time-consuming tracking
流式结构化数据计算语言的进化与新选择
The growth path of a 40W test engineer with an annual salary, which stage are you in?
用 Antlr 重构脚本解释器
小目标检测3_注意力机制_Self-Attention
支持各种文件快速重命名最简单的小技巧
测试用例很难?有手就行
go 操作MySQL之mysql包
2.1-梯度下降
2022-08-10 mysql/stonedb-慢SQL-Q16-耗时追踪
Redis source code-String: Redis String command, Redis String storage principle, three encoding types of Redis string, Redis String SDS source code analysis, Redis String application scenarios
关于Excel实现分组求和最全文档
pyqt5实现仪表盘
1.2-误差来源
redis operation