This repository was archived by the owner on Aug 13, 2024. It is now read-only.
File tree 2 files changed +91
-0
lines changed
2 files changed +91
-0
lines changed Original file line number Diff line number Diff line change
1
+ import java .math .BigInteger ;
2
+
3
+ /**
4
+ * @author medany
5
+ */
6
+
7
+ public class FibonacciNumbers {
8
+ public BigInteger solve (int n ) {
9
+ return fibonacci (n );
10
+ }
11
+
12
+ public BigInteger solveNoRecursion (int n ) {
13
+ return fibonacciNoRecursion (n );
14
+ }
15
+
16
+ private BigInteger fibonacci (int n ) {
17
+ if (n <= 1 ) {
18
+ return BigInteger .valueOf (n );
19
+ }
20
+ return fibonacci (n - 1 ).add ((fibonacci (n - 2 )));
21
+ }
22
+
23
+ private BigInteger fibonacciNoRecursion (int x ) {
24
+ if (x == 0 || x == 1 ) {
25
+ return BigInteger .valueOf (x );
26
+ } else {
27
+ BigInteger a = BigInteger .ZERO , b = BigInteger .ONE ;
28
+ BigInteger r = BigInteger .ZERO ;
29
+ for (int i = 2 ; i <= x ; i ++) {
30
+ r = a .add (b );
31
+ a = b ;
32
+ b = r ;
33
+ }
34
+ return r ;
35
+ }
36
+ }
37
+ }
Original file line number Diff line number Diff line change
1
+ import static org .junit .Assert .assertEquals ;
2
+
3
+ import java .math .BigInteger ;
4
+
5
+ import org .junit .Test ;
6
+
7
+ /**
8
+ * @author medany
9
+ */
10
+
11
+ public class FibonacciNumbersTest {
12
+
13
+ @ Test
14
+ public void Test_1 () {
15
+ FibonacciNumbers alg = new FibonacciNumbers ();
16
+
17
+ BigInteger actual = alg .solve (1 ), expected = BigInteger .ONE ;
18
+
19
+ System .out .println (actual );
20
+ assertEquals (expected , actual );
21
+ }
22
+
23
+ @ Test
24
+ public void Test_2 () {
25
+ FibonacciNumbers alg = new FibonacciNumbers ();
26
+
27
+ BigInteger actual = alg .solve (5 ), expected = BigInteger .valueOf (5 );
28
+
29
+ System .out .println (actual );
30
+ assertEquals (expected , actual );
31
+ }
32
+
33
+ @ Test
34
+ public void Test_3 () {
35
+ FibonacciNumbers alg = new FibonacciNumbers ();
36
+
37
+ BigInteger actual = alg .solve (10 ), expected = BigInteger .valueOf (55 );
38
+
39
+ System .out .println (actual );
40
+ assertEquals (expected , actual );
41
+ }
42
+
43
+ @ Test
44
+ public void Test_4 () {
45
+ FibonacciNumbers alg = new FibonacciNumbers ();
46
+
47
+ BigInteger actual = alg .solveNoRecursion (1000 );
48
+ BigInteger expected = new BigInteger (
49
+ "43466557686937456435688527675040625802564660517371780402481729089536555417949051890403879840079255169295922593080322634775209689623239873322471161642996440906533187938298969649928516003704476137795166849228875" );
50
+
51
+ System .out .println (actual );
52
+ assertEquals (expected , actual );
53
+ }
54
+ }
You can’t perform that action at this time.
0 commit comments