Saturday, December 1, 2012

Taxicab Number Test

My take on a taxicab number test routine. The original exercise can be found here.

#!/usr/bin/php
<?php

if ($argc != 2) {
   echo "Usage cube.php <number>".PHP_EOL;
   exit;
}
$num = $argv[1];

echo "Finding cubes less than ".$num.PHP_EOL;

$factor = 1;
$arr = array();
$bottom = array();
$top = array();
$half = floor($num/2);
//Modified the below loop to parition the cubes while its generating them.
//Thus preventing another loop to partition the cubes
do {
   $cube = pow($factor,3);
   if ($cube <= $half) {
      $bottom[$cube] = $factor;
   } else {
      $top[$factor] = $cube;
   }
   $factor++;
} while ($cube < $num);

echo "Found ".count($top)." cubes > lower half of list".PHP_EOL;
echo "Found ".count($bottom)." cubes <= lower half of list".PHP_EOL;
$total = (count($top)+count($bottom));
$perc = count($top)/$total;
echo "Only testing ".(round($perc*100,2))."%".PHP_EOL;

foreach ($top as $factor => $product) {
   $remainder = $num-$product;
   if (isset($bottom[$remainder])) {
      echo "Found ".$factor."^3 + ".$bottom[$remainder]."^3 = ".$num.PHP_EOL;
   }
}

1 comment:

  1. i read this blog, so it can help for all types of people, if any one wants that make his journey with all of his comfort,so visit this one
    http://urcabservice.com

    ReplyDelete