HiveBrain v1.2.0
Get Started
← Back to all entries
patternphpMinor

Draw the table like 6³ = 3³ + 4³ + 5³ to 100³ = 35³ + 70³ + 85³

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
85³the100³drawlike35³table70³

Problem

I want to draw the table like this:

6³ = 3³ + 4³ + 5³
9³ = 1³ + 6³ + 8³
12³ = 6³ + 8³ + 10³
18³ = 2³ + 12³ + 16³
18³ = 9³ + 12³ + 15³
19³ = 3³ + 10³ + 18³
20³ = 7³ + 14³ + 17³
.....
100³ = 35³ + 70³ + 85³


I've tried this:

$start = microtime(true);
funcC(100);
echo microtime(true) - $start;

function funcC($n){

$tnum = 3;
$s = '³';

$testmax = $n-$tnum;
$p3a = array();

$numlist = array_fill(0, 10, array());

for ($i = 0; $i $ipow){break;}

$diff = $ipow - ($p3a[$j]+$p3a[$k]);
$diff_t = $diff%10;

if(isset($numlist[$diff_t][$diff]) && $numlist[$diff_t][$diff]>$k ){

echo " $i$s = $j$s + $k$s + ".$numlist[$diff_t][$diff].$s.'
'.PHP_EOL;
break;
}
}
}
}
}


It is ok, but I want to know a faster way of doing this.

This code uses 0.59064292907715 as test code here.

Solution

I would make a few changes for readability:

  • Rename:



  • $p3a$cubes



  • $numlist$cubeRoots



  • Hard-code $tnum. It's not going to vary anyway, since it wasn't a parameter.



  • Eliminate $testmax. It's not worth the effort to save a few loop iterations.



  • More generous horizontal spacing. (You use lots of newlines in your source code, but need more spaces.)



Changing $numlist from a two-level array to a 1-dimensional array results in better readability as well as a performance improvement.

$i $i $i is simpler and faster than pow($i, 3).

Changing the termination condition of your inner loop results in an even more dramatic performance improvement.

Overall, this completes in about 1/3 of the time of the original code:

function funcC($n) {
    $exp = '³';

    $cubes = array();
    $cubeRoots = array();

    for ($i = 0; $i = $cubes[$k]; $k++) {
                if (isset($cubeRoots[$diff])) {
                    echo " $i$exp  =  $j$exp + $k$exp + " . $cubeRoots[$diff] . $exp . '' . PHP_EOL;
                    break;
                }
            }
        }

    }

}

Code Snippets

function funcC($n) {
    $exp = '³';

    $cubes = array();
    $cubeRoots = array();

    for ($i = 0; $i <= $n; $i++) {
        $j = $i * $i * $i;
        $cubes[$i] = $j;
        $cubeRoots[$j] = $i;
    }

    for ($i = 3; $i <= $n; $i++) {

        for ($j = 1; $j <= $i; $j++) {
            for ($k = $j; ($diff = $cubes[$i] - $cubes[$j] - $cubes[$k]) >= $cubes[$k]; $k++) {
                if (isset($cubeRoots[$diff])) {
                    echo " $i$exp  =  $j$exp + $k$exp + " . $cubeRoots[$diff] . $exp . '<br>' . PHP_EOL;
                    break;
                }
            }
        }

    }

}

Context

StackExchange Code Review Q#41179, answer score: 7

Revisions (0)

No revisions yet.