Java實例——計算 1+2!+3!+...+20!的和


計算 1+2!+3!+...+20!的和

1、使用嵌套循環實現

public class FactorialAdd {
    public static void main(String[] args) {
        //計算 1+2!+3!+...+20!的和
        System.out.println(" 1+2!+3!+...+20!的和為:"+factAdd());

    }
    //使用嵌套循環計算 1+2!+3!+...+20!的和、
    public static double factAdd(){
        double sum = 0;
        for(int i = 1 ; i <= 20 ; i++){
            int result = 1;
            for(int j = 1 ; j <= i; j++){
                result *= j;
            }
            sum += result;
        }
        return sum;
    }
}

 

2、使用遞歸實現

public class FactorialAdd {
    public static void main(String[] args) {
        //計算 1+2!+3!+...+20!的和
        System.out.println(" 1+2!+3!+...+20!的和為:"+factAdd());

    }
    //和計算
    public static double factAdd(){
       double result = 0;
        for(int i = 1 ; i <= 20 ; i++){
            result += fact(i);
        }
        return result;
    }
    //階乘計算
    public static int fact(int n){
       if(n == 1){
           return 1;
        }else{
            return n*fact(n-1);
        }
    }
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM