@@ -28,17 +28,36 @@ export function compareStrings(a: string, b: string): number {
28
28
* @return The factorial of n.
29
29
*/
30
30
export function computeFactorial ( n : number ) : number {
31
- return 0 ;
31
+ if ( n === 0 || n === 1 ) {
32
+ return 1 ;
33
+ }
34
+ if ( n < 0 ) {
35
+ return 0 ;
36
+ }
37
+ let result = 1 ;
38
+ for ( let i = 2 ; i <= n ; i ++ ) {
39
+ result *= i ;
40
+ }
41
+ return result ;
32
42
}
33
-
34
43
/**
35
44
* Returns an array of the first `n` Fibonacci numbers starting from 1.
36
45
*
37
46
* @param n The first `n` of Fibonacci values to compute.
38
47
* @return An array containing the first `n` Fibonacci values.
39
48
*/
40
49
export function getFirstNFibonacciNumbers ( n : number ) : number [ ] {
41
- return [ ] ;
50
+ if ( n <= 0 ) {
51
+ return [ ] ;
52
+ }
53
+ if ( n === 1 ) {
54
+ return [ 1 ] ;
55
+ }
56
+ const Fibonacci : number [ ] = [ 1 , 1 ] ;
57
+ for ( let i = 2 ; i < n ; i ++ ) {
58
+ Fibonacci . push ( Fibonacci [ i - 1 ] + Fibonacci [ i - 2 ] ) ;
59
+ }
60
+ return Fibonacci ;
42
61
}
43
62
44
63
/**
@@ -62,12 +81,17 @@ export function binarySearch(
62
81
}
63
82
64
83
const pivotIndex = Math . floor ( ( start + end ) / 2 ) ; // The index in the middle of the array.
65
-
66
- // TODO(you): Finish implementing this algorithm
67
-
68
- // If values[pivotIndex] is equal to value then return `pivotIndex`.
69
- // Else if values[pivotIndex] is greater than the value, then
70
- // call `binarySearch(values, start, pivotIndex - 1, value)` and return its value;
71
- // Else call `binarySearch(values, pivotIndex + 1, end, value)` and return its value.
72
- return - 1 ;
84
+ if ( values [ pivotIndex ] === value ) {
85
+ return pivotIndex ;
86
+ } else if ( values [ pivotIndex ] > value ) {
87
+ return binarySearch ( values , start , pivotIndex - 1 , value ) ; // Search in the right half
88
+ } else {
89
+ return binarySearch ( values , pivotIndex + 1 , end , value ) ; // Search in the left half
90
+ }
73
91
}
92
+ // TODO(you): Finish implementing this algorithm
93
+
94
+ // If values[pivotIndex] is equal to value then return `pivotIndex`.
95
+ // Else if values[pivotIndex] is greater than the value, then
96
+ // call `binarySearch(values, start, pivotIndex - 1, value)` and return its value;
97
+ // Else call `binarySearch(values, pivotIndex + 1, end, value)` and return its value.
0 commit comments