Skip to content

Instantly share code, notes, and snippets.

@era269
Created November 27, 2018 21:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save era269/cdf811d2c6be2e810bdd8f2e0bbf65b1 to your computer and use it in GitHub Desktop.
Save era269/cdf811d2c6be2e810bdd8f2e0bbf65b1 to your computer and use it in GitHub Desktop.
sum of great numbers
<?php
$a = '2334684234234234234234234234234';
$b = '593444444444444444444444444';
$tab = strlen($a) > strlen($b)
? strlen($a)
: strlen($b);
printf("\n%' {$tab}s\n", $a);
echo("+\n");
printf("%' {$tab}s\n", $b);
printf("%'_{$tab}s\n", '_');
printf("%' {$tab}s\n", sum($a, $b));
//-----------------------------------------
$a = '1';
$b = '2';
printf("\n%' 30s\n", $a);
echo("+\n");
printf("%' 30s\n", $b);
printf("%'_30s\n", '_');
printf("%' 30s\n", sum($a, $b));
//=========================================
function sum(string $a, string $b)
{
$posA = strlen($a) - 1;
$posB = strlen($b) - 1;
$r = array();
$posR = 0;
$rest = 0;
while ($posA >= 0 and $posB >= 0) {
$r[$posR] = (string)($a[$posA] + $b[$posB] + $rest);
processRest($r[$posR], $rest);
$posA--;
$posB--;
$posR++;
}
//--we have a first part of number at rest, if one number longer
if ($posA > $posB) {
$restNumber = $a;
$restPos = $posA;
} elseif ($posA < $posB) {
$restNumber = $b;
$restPos = $posB;
} else {
$restNumber = '';
$restPos = -1;
}
while ($restPos >= 0) {
$r[$posR] = (string)($restNumber[$restPos] + $rest);
processRest($r[$posR], $rest);
$restPos--;
$posR++;
}
//--revert result of sum and not forget rest
return $rest
? ($rest . strrev(implode($r)))
: strrev(implode($r));
}
//--calculate and save rest to the next step
function processRest(&$sum, &$rest)
{
$rest = 0;
if ($sum > 9) {
$rest = $sum[0];
$sum = $sum[1];
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment