此為演算法教學練習,展示如何僅用遞增運算子 (++) 構建加減乘除邏輯,不具生產環境實用性(效率極低),僅供理解運算本質。
function add($a, $b) {
for ($i = 0; $i < $b; $i++) {
$a++;
}
return $a;
}
// add(4, 2) => 6
function subtract($a, $b) {
$count = 0;
while ($b != $a) {
$b++;
$count++;
}
return $count;
}
// subtract(10, 3) => 7
// 前提:a >= b >= 0
function multiply($a, $b) {
$result = 0;
for ($j = 0; $j < $b; $j++) {
$result = add($result, $a);
}
return $result;
}
// multiply(9, 3) => 27
function divide($dividend, $divisor) {
$quotient = 0;
$product = 0;
while ($product < $dividend) {
$quotient++;
$product = multiply($divisor, $quotient);
}
// 注意:此處未處理餘數與精確商,僅示範邏輯
return $quotient;
}
// divide(16, 2) => 8
<?php
function add($a, $b) {
for ($i = 0; $i < $b; $i++) $a++;
return $a;
}
function subtract($a, $b) {
$c = 0;
while ($b != $a) { $b++; $c++; }
return $c;
}
function multiply($a, $b) {
$c = 0;
for ($j = 0; $j < $b; $j++) $c = add($c, $a);
return $c;
}
function divide($d, $e) {
$k = 0; $f = 0;
while ($f < $d) { $k++; $f = multiply($e, $k); }
return $k;
}
echo "4 + 2 = " . add(4, 2) . "\n";
echo "10 - 3 = " . subtract(10, 3) . "\n";
echo "9 * 3 = " . multiply(9, 3) . "\n";
echo "16 / 2 = " . divide(16, 2) . "\n";
--) 與符號判斷