Basic Java Recursion Method

后端 未结 5 1022
别跟我提以往
别跟我提以往 2020-12-07 04:33

I am having a lot of trouble with this basic recursion problem in java; any pointers would be great.

\"Write a static recursive method to print out th

5条回答
  •  爱一瞬间的悲伤
    2020-12-07 05:14

    A recursive solution: Seq(1) is the first element of the sequence .... Seq(n-th)

    public static void main(String args[]) throws Exception {
        int x = Seq(3); //x-> 18
    }
    
    public static int Seq(int n){
        return SeqRec(n);
    }
    
    private static int SeqRec(int n){
        if(n == 1)
            return 2;
        else return SeqRec(n - 1) * 3;
    }
    

    Non-Recursive solution:

    public static int Non_RecSeq(int n){
        int res = 2;
    
        for(int i = 1; i < n; i ++)
            res *= 3;
    
        return res;
    }
    
    public static void main(String args[]) throws Exception {
        int x = Non_RecSeq(3); //x-> 18
    }
    

提交回复
热议问题