简体   繁体   中英

factorial recursion “visualized” in java

So I have this basic factorial calculator in java but I am having trouble modifying it to fit the exercise. It says: Modify the factorial method to print its local variable and recursive-call parameter. For each recursive call,display the outputs on a separate line and add a level of indentation. I think Im having trouble understanding where the print statements should go. So does local variable = number and recursion call parameter = number-1. Here is my code so far.

public class Factorial {
    private static String s1="";
    public static long factorial(long number,long save) {


    if (number <= 1) { //test for base case
        System.out.printf("%s%d! = %d*%d!=  ",s1,save,save,save-1);
        s1 = s1 +" ";
        return 1;
    }
    else{ //recursion step
        return number * factorial(number - 1,save);
    }
}

//output factorial for values 0-21
public static void main(String[] args) {
    //calculate factorials 0-21
            for (int counter = 0; counter <= 21; counter++){
                long x = factorial(counter,counter);
        System.out.printf("%d%n",x);
    }
}

}

I think Im having trouble understanding where the print statements should go.

Yes, indeed. As you can see, the exercise states

Modify the factorial method to print its local variable and recursive-call parameter.

So, modify factorial instead of main . This way, each time factorial is invoked, you get a new line printed out, just as the exercise asks.

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