File tree Expand file tree Collapse file tree
src/in/knowledgegate/dsa/recursion Expand file tree Collapse file tree Original file line number Diff line number Diff line change 1+ package in .knowledgegate .dsa .recursion ;
2+
3+ /**
4+ * Factorial
5+ * n! = n X (n-1) X ..... X 1
6+ * F(0) = 1
7+ * F(1) = 1
8+ * F(2) = 2
9+ * F(3) = 6 = 3 * 2
10+ * F(n) = n * F(n-1), n >= 1
11+ */
12+ public class Factorial {
13+ public int fact (int n ) {
14+ if (n == 0 || n == 1 ) return 1 ;
15+ return n * fact (n -1 );
16+ }
17+ }
Original file line number Diff line number Diff line change 1+ package in .knowledgegate .dsa .recursion ;
2+
3+ /**
4+ * The Fibonacci numbers, commonly denoted F(n)
5+ * form a sequence, called the Fibonacci sequence,
6+ * such that each number is the sum of the two
7+ * preceding ones, starting from 0 and 1. That is,
8+ *
9+ * F(0) = 0, F(1) = 1
10+ * F(n) = F(n - 1) + F(n - 2), for n > 1.
11+ * Given n, calculate F(n).
12+ *
13+ *
14+ * Example 1:
15+ * Input: n = 2
16+ * Output: 1
17+ * Explanation: F(2) = F(1) + F(0) = 1 + 0 = 1.
18+ *
19+ * Example 2:
20+ * Input: n = 3
21+ * Output: 2
22+ * Explanation: F(3) = F(2) + F(1) = 1 + 1 = 2.
23+ *
24+ * Example 3:
25+ * Input: n = 4
26+ * Output: 3
27+ * Explanation: F(4) = F(3) + F(2) = 2 + 1 = 3.
28+ *
29+ *
30+ * Constraints:
31+ * 0 <= n <= 30
32+ */
33+ public class Fibonacci {
34+ public int fibRecursive (int n ) {
35+ if (n == 0 || n == 1 ) return n ;
36+ return fibRecursive (n - 1 ) +
37+ fibIterative ( n - 2 );
38+ }
39+
40+ public int fibIterative (int n ) {
41+ if (n == 0 || n == 1 ) return n ;
42+ int first = 0 , second = 1 ;
43+ for (int i = 1 ; i < n ; i ++) {
44+ int next = first + second ;
45+ first = second ;
46+ second = next ;
47+ }
48+ return second ;
49+ }
50+ }
You can’t perform that action at this time.
0 commit comments