1.设计一个方法,传入int类型的数字n,求n的阶乘
import java.util.Scanner;
public class test03 {
/*需求:设计一个方法,传入int类型的数字n,求n的阶乘
分析:
5! = 1*2*3*4*5 --> 5! = 4! * 5
4! = 1*2*3*4 --> 4! = 3! * 4
3! = 1*2*3 --> 3! = 2! * 3
2! = 1*2 --> 2! = 1! * 2
1! = 1 --> 1! = 1
找规律 -> n! = (n-1)! * n;
找出口 -> 1! = 1**/
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("请输入所求阶乘的数字:");
System.out.println(getFactorial(sc.nextInt()));
}
public static int getFactorial(int n){
if (n==1){
return 1;
}else {
return getFactorial(n-1)*n;
}
}
}
2.不死神兔
import java.util.Scanner;
public class test04 {
/*
需求:不死神兔(斐波那契数列/黄金分割数列)
有一对兔子,从出生后第三个月起每个月都生一对兔子,
小兔子长到第三个月后每个月又生一对兔子,假如兔子都不死,
问第n个月的兔子对数为多少?
找规律:除了第一个月和第二个月,其余月兔子的对数都等于上个月+上上个月的兔子对数
找出口:第一个月和第二个月兔子的个数都是1
**/
public static void main(String[] args) {
System.out.println("你想知道几个月后的兔子数量:");
Scanner sc=new Scanner(System.in);
System.out.println(getRabbit(sc.nextInt()));
}
public static int getRabbit(int month){
if (month==1 || month==2){
return 1;
}else {
return getRabbit(month-1)+getRabbit(month-2);
}
}
}