尾递归(未完成)

2019-10-18  本文已影响0人  Robin92

求n!(阶乘)
求1! + 2! + 3! + ... + n!,注意执行效率

普通递归:

public static long calc(int n){
    if (n == 1) 
        return 1;
    else
        return calc(n-1) * n;
}

尾递归:

public static int calc(int n, int a) {
    if (n<=0) {
        return 0;
    } else if (n==1) {
        return a;
    } else {
        return calc(n-1, n*a);
    }

}
评分标准:注意这是陷阱,如果简单循环20遍调用a)中的方法,重复计算,效率不高。得2分。

public static long calc(int n) {
    long sum = 0;
    long lastResult = 1;
    for (int i = 0; i < n; i++) {
        lastResult = lastResult * (i + 1);
        sum += lastResult;
    }
    return sum;
}


上一篇 下一篇

猜你喜欢

热点阅读