From f5ef44c5be4ea6d4e3137014aa5788236eab4b6d Mon Sep 17 00:00:00 2001 From: Lubos Kolouch Date: Sat, 26 Feb 2022 13:11:09 +0100 Subject: feat(lubos-kolouch/php/ch-1.php): Challenge 153 Task 1 PHP LK --- challenge-153/lubos-kolouch/php/ch-1.php | 59 ++++++++++++++++++++++++++++++++ 1 file changed, 59 insertions(+) create mode 100644 challenge-153/lubos-kolouch/php/ch-1.php diff --git a/challenge-153/lubos-kolouch/php/ch-1.php b/challenge-153/lubos-kolouch/php/ch-1.php new file mode 100644 index 0000000000..7b7c50e199 --- /dev/null +++ b/challenge-153/lubos-kolouch/php/ch-1.php @@ -0,0 +1,59 @@ +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"); -- cgit