Java recursion 5! Implementation code of
- 2020-06-15 08:32:56
- OfStack
Topic: Recursion method to find 5! .
Program analysis: recursive formula: fn=fn_1*4!
Program design:
import java.util.Scanner;
public class Ex22 {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
int n = s.nextInt();
Ex22 tfr = new Ex22();
System.out.println(tfr.recursion(n));
}
public long recursion(int n) {
long value = 0 ;
if(n ==1 || n == 0) {
value = 1;
} else if(n > 1) {
value = n * recursion(n-1);
}
return value;
}
}
Method 2 USES recursive method to find 5! .
public class lianxi22 {
public static void main(String[] args) {
int n = 5;
rec fr = new rec();
System.out.println(n+"! = "+fr.rec(n));
}
}
class rec{
public long rec(int n) {
long value = 0 ;
if(n ==1 ) {
value = 1;
} else {
value = n * rec(n-1);
}
return value;
}
}