Skip to content

Instantly share code, notes, and snippets.

@jehoshua02
Created October 2, 2012 22:18
Show Gist options
  • Select an option

  • Save jehoshua02/3823680 to your computer and use it in GitHub Desktop.

Select an option

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
<?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