Last active
September 28, 2015 00:32
-
-
Save felds/3942554e08d73fbe5997 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <?php | |
| /** | |
| * Usage: | |
| * ms(12345, 3) # returns "37035" | |
| * ms(999, 3) # returns "2997" | |
| * ms("1111", 24) # returns "26664" | |
| * | |
| * @param int|stirng $s A string containing a positive integer | |
| * @param int $m The multiplier | |
| * @return string The product of the multiplication (as a string) | |
| */ | |
| function ms($s, $m) { | |
| $l = str_split($s); | |
| $cs = 0; | |
| $r = array_reduce(array_reverse($l), function ($c, $x) use ($m, &$cs) { | |
| $p = $x * $m + $cs; | |
| if ($p > 9) { | |
| $cs = substr($p, 0, -1); // tens | |
| $p = substr($p, -1); | |
| } else { | |
| $cs = 0; | |
| } | |
| return $p . $c; | |
| }, ""); | |
| if ($cs) $r = $cs . $r; | |
| return $r; | |
| } | |
| function fac($n) { | |
| $x = 1; | |
| for ($i = $n; $i > 1; $i--) { | |
| $x = ms((string) $x, $i); | |
| } | |
| return $x; | |
| } | |
| var_dump("fac(13)", $s = fac(13), $s === "6227020800"); | |
| var_dump("fac(100)", $s = fac(100), $s === "93326215443944152681699238856266700490715968264381621468592963895217599993229915608941463976156518286253697920827223758251185210916864000000000000000000000000"); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment