Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Appearance settings

Latest commit

 

History

History
History
51 lines (34 loc) · 1.19 KB

File metadata and controls

51 lines (34 loc) · 1.19 KB
Copy raw file
Download raw file
Open symbols panel
Edit and raw actions
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
import java.util.Scanner;
class Factorial3 { // The factorial of five (5 x 4 x 3 x 2 x 1) is 120. Four factorial (4 x 3 x 2 x 1) is 24.
// This is a recursive function.
int factR(int n){
int result;
if(n == 1) return 1;
// Execute the recursive call to factR().
result = factR(n-1) * n; // The factorial of a number n is n*n-1 *n-2*... *1.
return result;
}
// This is an iterative equivalent.
int factI(int n) {
int t, result;
result = 1;
for(t = 1 ; t <= n ; t++)
result *= t ;
return result;
}
}
public class Recursion3 {
public static void main(String[] args) {
int input, result, result2;
System.out.println("Enter the number to count its factorial: ");
Scanner readScanner = new Scanner(System.in);
input = readScanner.nextInt();
readScanner.close();
System.out.println("Your input is " + input);
Factorial3 factorial3 = new Factorial3();
result = factorial3.factR(input);
System.out.println("The factorial of " + input + " is " + result + " , using recursive function.");
result = factorial3.factI(input);
System.out.println("The factorial of " + input + " is " + result + " , using iterative function.");
}
}
Morty Proxy This is a proxified and sanitized view of the page, visit original site.