1 package com.dvp.tutoriel.fibonacci;
2
3 import java.util.HashMap;
4 import java.util.Map;
5
6 public class MaCalculette implements Calculette {
7
8 private static Map<Integer, Long> map = new HashMap<Integer, Long>();
9
10 private final static double NOMBRE_OR = 1.61803398874989;
11 private final static double RACINE_5 = 2.236067977499;
12
13 public Long fibonacciAvecNombreOr(Integer n) {
14
15 if (n <= 0) {
16 throw new IllegalArgumentException("On ne calcule que pour des nombres positifs");
17 }
18
19
20
21 if (n == 1 || n == 2) {
22 return 1L;
23 }
24
25 final double nominateur = Math.pow(NOMBRE_OR, n);
26
27 final double result = nominateur / RACINE_5;
28 return Math.round(result);
29 }
30
31 @Override
32 public Long fibonacci(Integer n) {
33
34
35 if (n <= 0) {
36 throw new IllegalArgumentException("On ne calcule que pour des nombres positifs");
37 }
38
39
40
41 if (n == 1 || n == 2) {
42 return 1L;
43 }
44
45
46
47 Long valeur = map.get(n);
48 if (valeur != null) {
49 return valeur;
50 }
51
52
53 valeur = fibonacci(n - 1) + fibonacci(n - 2);
54 map.put(n, valeur);
55 return valeur;
56
57 }
58
59 }