Recursive understanding of the understanding of time

  public static int fun(int n) {
    if (n<=1) return 1;
    else return (n + fun(n-1));   
  }

Why fun(6)returns 21?

As I present recursion, I follow:

6 + 5 = 11
5 + 4 = 9
4 + 3 = 7
3 + 2 = 5
2 + 1 = 3
1       1
11 + 9 + 7 + 5 + 3 + 1 = 36

Can someone explain to me what is going on here?

- edited the deleted one System.out.println(), forgot to delete it when I posted the code.

I tried the following:

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

2 * fun(4)
2 * (2 * fun(3))
2 * (2 * (2 * fun(2)))
2 * (2 * (2 * (2 * fun(1))))
2 * 2 * 2 * 2 * 2 = 32

Is this the right way to render?

+4
source share
4 answers

Each call funcompletes execution return n + fun(n-1);. So let's see what happens.

You call fun(6)which ...

takes on a value 6 + fun(5)that ...

matters 6 + (5 + fun(4))which ...

matters 6 + (5 + (4 + fun(3)))which ...

takes on a value 6 + (5 + (4 + (3 + fun(2))))that ...

evaluated as 6 + (5 + (4 + (3 + (2 + fun(1))))), and since fun(1) = 1, this

6 + 5 + 4 + 3 + 2 + 1, 21.

+6

, :

fun(6) =
6 + fun(5) =
6 + 5 + fun(4) =
...
6 + 5 + 4 + 3 + 2 + 1 =
21

(n <= 1). ,

+6
fun(6) = 6 + fun(5)
       = 6 + 5 + fun(4)
       = 6 + 5 + 4 + fun(3)
       ...
       = 6 + 5 + 4 + 3 + 2 + 1 = 21
+1
source

The first line is "System.out.println (n +" "+ (n-1)); shows only the values โ€‹โ€‹of the variable" n "and DOES NOT CONTAIN ANY ARITHMETIC OPERATIONS.

Steps of this function:

6> 1 like this: 6 + fun (5),

5> 1 like this: 6 + 5 + fun (4),

4> 1 like this: 6 + 5 + 4 + fun (3),

3> 1 like this: 6 + 5 + 4 + 3 + fun (2),

2> 1 like this: 6 + 5 + 4 + 3 + 2 + fun (1),

1> = 1 like this: 6 + 5 + 4 + 3 + 2 + 1

and SUM: 6 + 5 + 4 + 3 + 2 + 1 = 21

I hope that my explanations will be useful to you.

+1
source

Source: https://habr.com/ru/post/1656876/


All Articles