[编程题] 递归实现等差数列和阶乘

[编程题] 递归实现等差数列和阶乘

需求

使用递归实现等差数列

Java代码

package nlikou;

/**
 * @author jiyongjia
 * @create 2020/7/26 - 18:40
 * @descp:
 */
public class P11_jiecheng {
    public static void main(String[] args) {
        //三个参数分别代表首先,公差,项数
        int f1 = f(1,1,4);
        System.out.println(f1);  //10
    }


    public static int f(int a,int d,int n){
        if(n==1) {
            return a;
        }
        return a+(n-1)*d+f(a,d,n-1);
    }
}

输出输出

输出:10


递归实现阶乘

代码

package nlikou;

/**
 * @author jiyongjia
 * @create 2020/7/26 - 18:54
 * @descp:
 */
public class P112_阶乘 {
    public static void main(String[] args) {
        //三个参数分别代表首先,公差,项数
        int f1 = f(3);
        System.out.println(f1);  //6
    }


    public static int f(int n){
        if(n==1) {
            return 1;
        }
        return n*f(n-1);
    }
}

输出:6

原文地址:https://www.cnblogs.com/jiyongjia/p/13381443.html