Recursive algorithm: calculate the value of 1+2+3+……+n

Recursive algorithm: calculate the value of 1+2+3+……+n

public class Main {

    public static int test(int n){
        int temp = 0;
        if (n-1>0){
            temp = n + test(n-1);
        }else {
            temp = n;
        }
        return temp;
    }

    public static void main(String[] args) {
        int test = test(10);
        System.out.println(test);
    }
}

Test Results:

55

To understand the algorithm, you need to understand recursion. Many people only know that recursion calls themselves, but they do not understand the relationship between the scope of their own variables. In fact, every time you call yourself, its variables are independent and do not affect each other. If you really can’t understand it, just Think of all the recursion times, each call as not calling itself, but another independent method.

For example, we can write the above test() method into 10 test() methods, distinguished by 1, 2, 3...10, and then write the above code as a loop, and each loop calls a different method, and the execution is the same The logic of, can get the same result, which will help my understanding of recursion.

In fact, recursion is really not that difficult. You think that difficulty may be a kind of psychological obstacle. You didn't think about it and lacked the spirit of exploration. You only need to think of each recursion as calling a method once, this method gets a return result, and this result then calls a method with the same logic as yourself, and continues to participate in the calculation, if you go back and forth repeatedly!