複習篇 -- 遞歸和非遞歸方法實現N!

import java.util.Scanner;
class Recursion{
    public static void main(String argv[]){
    
        System.out.println("chose the method to implement N! 1:recursion 2:not the recursion");
        
        int n=0;
        Scanner scanner = new Scanner(System.in);
        n = scanner.nextInt();
        if(n==1){
            System.out.println("input the n value: ");
            n = scanner.nextInt();
            System.out.println("the n! value are " + recursion(n));
            
        }else if(n==2){
            System.out.println("input the n value: ");
            n = scanner.nextInt();
            System.out.println("the n! value are " + noRecursion(n));
        }
        
    }
    
    /*the recursion to implement the n!*/    
    public static long recursion(int n){
        long res = 1;
        
        if(n<=0){
            res = 0;
            return res;
        }else if(n==1){
            res = 1;
        }else{
            res = recursion(n-1)*n;
        }
                
        return res;
        
    }
    
    /*the simple method  to implement the n!*/    
    public static long noRecursion(int n){
        long res = 1;
        if(n<=0){
            res = 0;
            return res;
        }else if(n==1){
            res = 1;
        }else{
            for(int i=1; i<=n; i++){
                res *= i;
            }
        }
        return res;
    }

}



實驗結果:


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章