当前位置:网站首页>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 } } }
边栏推荐
- 1003 I want to pass (20 points)
- 1002 Write the number (20 points)
- 【TA-霜狼_may-《百人计划》】图形3.7.2 command buffer简
- 3.1-分类-概率生成模型
- 欢迎加入sumarua网络安全交流社区
- [Recommender System]: Overview of Collaborative Filtering and Content-Based Filtering
- Use tf.argmax in Tensorflow to return the index of the maximum value of the tensor along the specified dimension
- Conditional statements in TF; where()
- Active users of mobile banking grew rapidly in June, hitting a half-year high
- 流式结构化数据计算语言的进化与新选择
猜你喜欢
随机推荐
动态代理学习
Break pad source code compilation--refer to the summary of the big blogger
klayout--导出版图为gds文件
零基础SQL教程: 基础查询 05
我的创作纪念日丨感恩这365天来有你相伴,不忘初心,各自精彩
About # SQL problem: how to set the following data by commas into multiple lines, in the form of column display
TF generates (feature, label) set through feature and label, tf.data.Dataset.from_tensor_slices
借问变量何处存,牧童笑称用指针,Go lang1.18入门精炼教程,由白丁入鸿儒,go lang类型指针(Pointer)的使用EP05
进阶-指针
Swagger简单使用
redis operation
IQUNIX A80 exploring TTC金粉 初体验
1081 Check Password (15 points)
1061 判断题 (15 分)
Pico neo3 Unity Packaging Settings
Serverless + domain name can also build a personal blog? Really, and soon
1051 Multiplication of Complex Numbers (15 points)
tf.cast(), reduce_min(), reduce_max()
1061 True or False (15 points)
初级软件测试工程师笔试试题,你知道答案吗?