| Total Complexity | 12 |
| Total Lines | 49 |
| Duplicated Lines | 0 % |
| Changes | 3 | ||
| Bugs | 0 | Features | 0 |
| 1 | <?php |
||
| 7 | class Pow |
||
| 8 | { |
||
| 9 | public static function myPow(float $x, int $n): float |
||
| 10 | { |
||
| 11 | if ($n === 0) { |
||
| 12 | return 1; |
||
| 13 | } |
||
| 14 | |||
| 15 | if ($n < 0) { |
||
| 16 | [$x, $n] = [1 / $x, -$n]; |
||
| 17 | } |
||
| 18 | |||
| 19 | if ($n % 2 === 0) { |
||
| 20 | $ans = self::myPow($x * $x, $n / 2); |
||
| 21 | } else { |
||
| 22 | $ans = $x * self::myPow($x * $x, intdiv($n, 2)); |
||
| 23 | } |
||
| 24 | |||
| 25 | return $ans; |
||
| 26 | } |
||
| 27 | |||
| 28 | public static function myPow2(float $x, int $n): float |
||
| 29 | { |
||
| 30 | if ($n < 0) { |
||
| 31 | [$x, $n] = [1 / $x, -$n]; |
||
| 32 | } |
||
| 33 | $y = 1; |
||
| 34 | while ($n) { |
||
| 35 | if ($n & 1) { // n % 2 === 1 |
||
| 36 | $y *= $x; |
||
| 37 | } |
||
| 38 | $x *= $x; // x = x ^ 2 |
||
| 39 | $n >>= 1; // n /= 2 |
||
| 40 | } |
||
| 41 | |||
| 42 | return $y; |
||
| 43 | } |
||
| 44 | |||
| 45 | public static function myPow3(float $x, int $n): float |
||
| 56 | } |
||
| 57 | } |
||
| 58 |