简体   繁体   中英

Recursion in Java factorial program

What I know about recursion is that it is that function calls itself and it has base condition where it stops. My professor wrote a program and he called that recursion is occurring in it and I said no, it's not. I am confused about it. So am asking you to clear my confusion. Program made by him is below in code:

int fact(int n) {
    if (n == 0) {
        return 1;
    }

    for (int i = n; i >= 1; i--) {
        s1.push(i);
    }
    return Return_result();

}

int Return_result() {
    int f = 1;
    while (s1.top != -1) {
        f = f * s1.pop();
    }
    return f;
}

You are right, there is no recursion in the presented code. It is an iterative approach.

Recursion is, if in f() method (in Java nomenclature) or a function (in general), you have a call to f() .

Recursive approach will look like this:

int fact(int n) {
    return (n <= 1) ? 1 : fact(n - 1) * n;
}

Or, using tail-recursion (also known as "tail call"):

int fact(int n) {
    return factTail(n, 1);
}

int factTail(int n, int accumulator) {
    return (n <= 1) ? accumulator : factTail(n - 1, n * accumulator);
}

Currently, JVM doesn't perform tail-recursion optimization, but this can change :

It's important to note that this isn't a bug in the JVM. It's an optimization that can be implemented to help functional programmers who use recursion, which is much more common and normal in those languages. I recently spoke to Brian Goetz at Oracle about this optimization, and he said that it's on a list of things to be added to the JVM, but it's just not a high-priority item. For now, it's best to make this optimization yourself, if you can, by avoiding deeply recursive functions when coding a functional language on the JVM.

first i want to explain some facts:

  1. Factorial is computed by the following formula : n! = n * n-1 * n-2 * n-3 * .....* 3 * 2 * 1 n! = n * n-1 * n-2 * n-3 * .....* 3 * 2 * 1
  2. Stack works in LIFO = last in first out or FILO = first in last out

so the code does the following it first puts all numbers from n to 1 in a stack then it pops each one and multiply it with the current result to get the factorial at the end

and by the way that is the iterative version for factorial (non-recursive), the recursive version will be like the following

int fact(int n)
{
    int result;

   if(n==1)
     return 1;

   result = fact(n-1) * n;
   return result;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM