Created
October 2, 2012 22:18
-
-
Save jehoshua02/3823680 to your computer and use it in GitHub Desktop.
Checks to see if an integer has an integer root given an integer power
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 | |
| function hasIntegerRoot($number, $power, &$root = null) { | |
| $root = round(pow($number, 1.0 / $power)); | |
| return round(pow($root, $power)) == $number; | |
| } | |
| function testHasIntegerRoot() | |
| { | |
| // calculate squares | |
| $number = 1; | |
| $last = 0; | |
| while ($last < 999) { | |
| $squares[] = $last = pow($number, 2); | |
| $number++; | |
| } | |
| // calculate cubes | |
| $number = 1; | |
| $last = 0; | |
| while ($last < 999) { | |
| $cubes[] = $last = pow($number, 3); | |
| $number++; | |
| } | |
| for ($i = 1; $i <= 999; $i++) { | |
| $isSquare = hasIntegerRoot($i, 2, $squareRoot); | |
| $isCube = hasIntegerRoot($i, 3, $cubeRoot); | |
| if ($isSquare && !in_array($i, $squares)) { | |
| echo "$i erroneously identified as perfect square.\n"; | |
| } | |
| if ($isCube && !in_array($i, $cubes)) { | |
| echo "$i erroneously identified as perfect cube.\n"; | |
| } | |
| if (!$isSquare && in_array($i, $squares)) { | |
| echo "$i erroneously not identified as perfect square.\n"; | |
| } | |
| if (!$isCube && in_array($i, $cubes)) { | |
| echo "$i erroneously not identified as perfect cube.\n"; | |
| } | |
| $numbers[$i] = array( | |
| 'square' => $isSquare, | |
| 'cube' => $isCube, | |
| ); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment