国产精品天干天干,亚洲毛片在线,日韩gay小鲜肉啪啪18禁,女同Gay自慰喷水

歡迎光臨散文網(wǎng) 會員登陸 & 注冊

java 遞歸recursion的使用

2022-07-14 17:00 作者:虛云幻仙  | 我要投稿

/**
* 測試遞歸recursion
*/

public class TestRecursion2 {
? ?public static int m = 0;
? ?public static int factorial(int n){
? ? ? ?//factorial階乘
? ? ? ?m++;
? ? ? ?if (m<n){
? ? ? ? ? ?return m*factorial(n);
? ? ? ?}else{
? ? ? ? ? ?m = 0;
? ? ? ? ? ?return n;
? ? ? ?}
? ?}

? ?public static void main(String[] args) {
? ? ? ?System.out.println(factorial(10));
? ? ? ?System.out.println(10*9*8*7*6*5*4*3*2);

? ?}
}

class TestRecursion3{
? ?//計算斐波那契數(shù)列 [1,2,3,5,8,13,21.....]每一位是前兩位的和
? ?public static int abc(int n) {
? ? ? ?//計算第n位的值
? ? ? ?if (n > 2) {
? ? ? ? ? ?return abc(n - 1) + abc(n - 2);
? ? ? ?} else if (n==2) {
? ? ? ? ? ?return 2;
? ? ? ?}else return 1;
? ?}

? ?public static int def(int n){
? ? ? ?if (n<2){
? ? ? ? ? ?return 1;
? ? ? ?}else if (n<3){
? ? ? ? ? ?return 2;
? ? ? ?}
? ? ? ?int a1 = 1;
? ? ? ?int a2 = 2;
? ? ? ?int result = a1+a2;
? ? ? ?for (int i =4;i<=n;i++){
? ? ? ? ? ?a1 = a2;
? ? ? ? ? ?a2 = result;
? ? ? ? ? ?result = a1+a2;
? ? ? ?}
? ? ? ?return result;
? ?}

? ?public static int ghi(int n){
? ? ? ?if (n<2){
? ? ? ? ? ?return 1;
? ? ? ?}else if (n<3){
? ? ? ? ? ?return 2;
? ? ? ?}
? ? ? ?int[] arr = new int[n];
? ? ? ?arr[0] = 1;
? ? ? ?arr[1] = 2;
? ? ? ?for (int i=2;i<n;i++){
? ? ? ? ? ?arr[i] = arr[i-1]+arr[i-2];
? ? ? ?}
? ? ? ?return arr[n-1];

? ?}

? ?public static void main(String[] args) {
? ? ? ?int n = new Random().nextInt(20)+1;
? ? ? ?System.out.println(n);
? ? ? ?System.out.println(abc(n));
? ? ? ?System.out.println(def(n));
? ? ? ?System.out.println(ghi(n));
? ?}
}

java 遞歸recursion的使用的評論 (共 條)

分享到微博請遵守國家法律
梓潼县| 龙门县| 阿勒泰市| 巢湖市| 岑溪市| 昌乐县| 宾阳县| 唐河县| 科技| 昌都县| 南漳县| 徐州市| 章丘市| 福建省| 怀柔区| 亳州市| 辛集市| 宁武县| 通道| 沙河市| 潜江市| 永兴县| 抚州市| 大丰市| 昆明市| 搜索| 宜宾县| 米脂县| 安泽县| 祁连县| 铜川市| 望都县| 交口县| 五指山市| 峨山| 黎川县| 阳江市| 铅山县| 呼伦贝尔市| 察隅县| 吉木萨尔县|