/
ch-1.php
61 lines (45 loc) · 1.48 KB
/
ch-1.php
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
52
53
54
55
56
57
58
59
60
61
<?php
class LeftFactCalculator {
public function __construct() {
# keep seen factorials in a cache to speed things up
$this->fact_cache = [0 => 1];
$this->left_fact_cache = [0 => 0];
}
public function calculate_factorial(int $what) {
if (array_key_exists($what, $this->fact_cache)) {
return $this->fact_cache[$what];
}
# let's utilize the fact that we are processing the numbers in sequence
$this->fact_cache[$what] = $what * $this->fact_cache[$what - 1];
return $this->fact_cache[$what];
}
public function calculate_left_fact(int $what) {
if (array_key_exists($what, $this->left_fact_cache)) {
return $this->left_fact_cache[$what];
}
# let's utilize the fact that we are processing the numbers in sequence
$this->left_fact_cache[$what] = $this->calculate_factorial($what - 1) + $this->left_fact_cache[$what - 1];
return $this->left_fact_cache[$what];
}
public function get_left_factorial(int $what) {
$output = [];
foreach (range(1, $what) as $i) {
$output[] = $this->calculate_left_fact($i);
}
return $output;
}
}
$calculator = new LeftFactCalculator();
array_diff($calculator->get_left_factorial(10), [
1,
2,
4,
10,
34,
154,
874,
5914,
46234,
409114,
]) == [] or throw new Exception("Failed test 1");
?>