Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

public class Factorial {
int factR(int n){
    int result;
    if(n==1)return 1;
    result=factR(n-1)*n;
    System.out.println("Recursion"+result);
    return result;
}

I know that this method will have the output of

  Recursion2
  Recursion6
  Recursion24
  Recursion120
  Recursive120

However, my question is how does java store the past values for the factorial? It also appears as if java decides to multiply the values from the bottom up. What is the process by which this occurs? It it due to how java stores memory in its stack?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
262 views
Welcome To Ask or Share your Answers For Others

1 Answer

http://www.programmerinterview.com/index.php/recursion/explanation-of-recursion/

The values are stored on Java's call stack. It's in reverse because of how this recursive function is defined. You're getting n, then multiplying it by the value from the same function for n-1 and so on, and so on, until it reaches 1 and just returns 1 at that level. So, for 5, it would be 5 * 4 * 3 * 2 * 1. Answer is the same regardless of the direction of multiplication.

You can see how this works by writing a program that will break the stack and give you a StackOverflowError. You cannot store infinite state on the call stack!

public class StackTest {
    public static void main(String[] args) {
        run(1);
    }

    private static void run(int index) {
        System.out.println("Index: " + index);
        run(++index);
    }
 }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share

548k questions

547k answers

4 comments

86.3k users

...