用递归法实现斐波那契序列、阶乘、阶乘的阶乘
- 斐波那契序列实现
- 规则:当前这个数值,等于其前两位数值的和,示例如:1 1 2 3 5 8 13 21 34…
- 实现方法:递归实现
- 递归实现的要点
- 终止条件
- 循环主体
- 具体代码实现
package com.tl.job005.algo;
public class FiberTest {
public static int fiber(int location){
if(location<1){
return -1;
}
if(location==1 || location==2){
return 1;
}else{
return fiber(location-1)+fiber(location-2);
}
}
public static void main(String[] args) {
System.out.println(fiber(-100));
System.out.println(fiber(1));
System.out.println(fiber(2));
System.out.println(fiber(5));
System.out.println(fiber(7));
}
}
- 阶乘的实现
- 规则:1的阶乘表示为1!=1,2!=21,3=32*1…
- 实现方法:递归实现
- 递归实现的要点
- 终止条件
- 循环主体
- 具体代码实现
- 规则:1的阶乘表示为1!=1,2!=21,3=32*1…
package com.tl.job005.algo;
/**
* 实现一阶阶乘
*
* @author zel
*
* @time:2019年3月19日
*/
public class FacTest {
public static long fac(int n) {
if (n < 1) {
return -1;
}
if (n == 1) {
return 1;
} else {
return n * fac(n - 1);
}
}
public static void main(String[] args) {
System.out.println(fac(-3));
System.out.println(fac(1));
System.out.println(fac(2));
System.out.println(fac(5));
}
}
- 阶乘的阶乘
- 规则:1的阶乘的阶乘表示为1!!=1,2!=2!*1!,3!!=3!*2!*1!..
- 实现方法:递归实现
- 递归实现的要点
- 终止条件
- 循环主体
- 具体代码实现
package com.tl.job005.algo;
/**
* 实现2阶阶乘
*
* @author zel
*
* @time:2019年3月19日
*/
public class FacFacTest {
public static long fac(int n) {
if (n < 1) {
return -1;
}
if (n == 1) {
return 1;
} else {
return n * fac(n - 1);
}
}
public static long facFac(int n) {
if (n < 1) {
return -1;
}
if (n == 1) {
return 1;
} else {
return fac(n) * facFac(n - 1);
}
}
public static void main(String[] args) {
System.out.println(facFac(-3));
System.out.println(facFac(1));
System.out.println(facFac(2));
System.out.println(facFac(5));
}
}
天亮教育是一家从事大数据云计算、人工智能、教育培训、产品开发、咨询服务、人才优选为一体的综合型互联网科技公司。
公司由一批BAT等一线互联网IT精英人士创建,
以"快乐工作,认真生活,打造IT职业技能教育的一面旗帜"为愿景,胸怀"让天下没有难找的工作"使命,
坚持"客户第一、诚信、激情、拥抱变化"的价值观,
全心全意为学员赋能提效,践行技术改变命运的初心。
更多学习讨论, 请加入
官方-天亮大数据交流-366784928
群二维码:
官方-天亮web前端交流-972788995
群二维码:
欢迎关注天亮教育公众号,大数据技术资料与课程、招生就业动态、教育资讯动态、创业历程分享一站式分享,官方微信公众号二维码:
天亮教育大数据官方群318971238,
天亮教育web前端官方群318971238,
爬虫、nlp技术qq群320349384
hadoop & spark & hive技术群297585251
教育培训官网:http://myhope365.com
项目研发业务尚云科技官网:http://shangyuninfo.com/
天亮教育公开课-从小白到大佬修成记-全系列视频地址:http://myhope365.com/news/index?id=66