求10!+11!+…+20! 的值

659人浏览 / 0人评论
求10!+11!+…+20! 的值
package com.admxj.factorial;
/*
 * 2015年12月9日20:57:14
 * 求和10!+11!+12!+13!***20!
 */
public class Day02 {
    public static void main(String[] args) {
        //定义起始变量和结束变量
        int begin = 10;
        int end = 20;
        long result = factorial_1(begin, end);
        System.out.println(ouputStr(begin,end)+result);
    }
    /*
     * 阶乘求和
     */
    public static long factorial_1(int begin, int end){
        if(begin >end){
            begin = begin^end;
            end = begin^end;
            begin = begin^end;
        }
        long sum = 0;
        for(int i = begin; i <= end; i++){ sum = sum + factorialRecursion(begin); begin++; } return sum; } /* * 求阶乘 */ public static long factorialRecursion(int n){ if(n == 1){ return 1; }else{ return n*factorialRecursion(n-1); } } /* * 获取字符串10!+11!+12!+13!***20! */ public static String ouputStr(int begin, int end){ if(begin >end){
            begin = begin^end;
            end = begin^end;
            begin = begin^end;
        }
        String str = "";
        if(begin == end){
            return str+ begin + "!=";
        }else{
            return str+ begin + "!+"+ouputStr(++begin, end);
        }
    }
}
第二种优化后
package com.admxj.factorial;
/*
 * 2015年12月9日21:31:01
 * 求和10!+11!+12!+13!***20!
 */
public class Day02Lin {
    public static void main(String[] args) {
        int begin = 10;
        int end = 20;
        System.out.println(factorial(begin,end));
    }
    public static long factorial(int begin, int end){
        long result = 0;
        for(;begin <= end; begin++){
            long sum = 1;
            for(int j = 1; j <= begin; j++){
                sum *=j;
            }
            result += sum;
        }
        return result;
    }
}
再次简化乘法运算
package com.admxj.factorial;
/*
 * 2015年12月9日21:31:01
 * 求和10!+11!+12!+13!***20!
 */
public class Day02Lin {
    public static void main(String[] args) {
        int begin = 10;
        int end = 20;
        System.out.println(factorial(begin,end));
    }
    public static long factorial(int begin, int end){
        int count = 0;
        long result = 0;
        long sum = 1;
        int p = begin;
        //判断是否为第一个数
        for(;p <= end; p++){
            if(begin == p){
                for(int j = 1; j <= p; j++){
                    sum *=j;
                    count++;
                }
            }else{
                sum *=p;
                //count++;
            }
            result += sum;
        }
        System.out.println("乘法次数:"+count);
        return result;
    }
}