当前位置:网站首页>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 } } }
边栏推荐
- 租房小程序
- leetcode:69. x 的平方根
- The softmax function is used in TF;
- Do you know the basic process and use case design method of interface testing?
- 【LeetCode】Summary of linked list problems
- 关于Excel实现分组求和最全文档
- 如何通过开源数据库管理工具 DBeaver 连接 TDengine
- Four operations in TF
- 分门别类输入输出,Go lang1.18入门精炼教程,由白丁入鸿儒,go lang基本数据类型和输入输出EP03
- 项目2-年收入判断
猜你喜欢

About # SQL problem: how to set the following data by commas into multiple lines, in the form of column display

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
4.1 - Support Vector Machines

Use tf.argmax in Tensorflow to return the index of the maximum value of the tensor along the specified dimension

【LeetCode】链表题解汇总

Square, multi-power, square root calculation in Tf
1.2 - error sources

Mysql JSON对象和JSON数组查询

CSDN21天学习挑战赛——封装(06)

9、Neural Sparse Voxel Fields
随机推荐
4.1-支持向量机
测试用例很难?有手就行
C Primer Plus(6) 中文版 第1章 初识C语言 1.6 语言标准
8、Mip-NeRF
如何通过开源数据库管理工具 DBeaver 连接 TDengine
【LeetCode】链表题解汇总
1106 2019 Sequence (15 points)
Four states of Activity
如何仅更改 QGroupBox 标题的字体?
查找最新人员工资和上上次人员工资的变动情况
我的创作纪念日丨感恩这365天来有你相伴,不忘初心,各自精彩
pyqt5实现仪表盘
oracle19c does not support real-time synchronization parameters, do you guys have any good solutions?
Two state forms of Service
Four startup modes of Activity
机器学习(三)多项式回归
机器学习(一)数据的预处理
Redis source code: how to view the Redis source code, the order of viewing the Redis source code, the sequence of the source code from the external data structure of Redis to the internal data structu
Machine Learning Summary (2)
IQUNIX A80 exploring TTC金粉 初体验