Core\BigInt::plus
$bigInt->plus(Core\BigInt $other): Core\BigInt$bigInt->plus( Core\BigInt $other, ): Core\BigInt
Returns the sum of this number and another one, as a new Core\BigInt.
The sum is always exact, however large the numbers are. When the sum of two int values is too large for an int, the addition throws an error. Use Core\BigInt when a total may grow that far.
plus does not change either number. It returns the result as a new number, so keep that result in a variable.
Good to know: $a + $b does not work on two Core\BigInt values, because + is only for plain numbers. plus is how you write it. To take a number away, use minus, or add a negative number.
Parameters
$otherCore\BigIntThe value to add.
Return value
Returns Core\BigInt. A BigInt equal to the sum.
Changelog
| Version | Change |
|---|---|
0.0.6 | Each Core\BigInt method that computes a new number is named for its result: plus, minus, multipliedBy, dividedBy, remainder, raisedTo, raisedToModulo, negated, shiftedLeft and shiftedRight. The old names were add, sub, mul, div, mod, pow, powMod, neg, shl and shr. |
Examples
Adding two numbers
<?nvs// Shows how to add two numbers, and that `plus` returns a new number instead of// changing the one you called it on.
var $first = Core\BigInt::of(120);var $second = Core\BigInt::of(23);
// This prints 143.echo $first->plus($second), "\n";
// `$first` still has the same value. This prints 120.echo $first, "\n";
// Adding a negative number takes it away. This prints 97.echo $first->plus(Core\BigInt::of(-23)), "\n";14312097Past what an int can hold
<?nvs// Shows the reason `Core\BigInt` exists. A sum that is too large for an `int`// stops an ordinary addition, and `plus` gives you the number.
int $largest = 9223372036854775807;
// `$largest + 1` throws an `ArithmeticError`. The error is caught here, so the// program goes on.try { echo $largest + 1, "\n";} catch (ArithmeticError $overflow) { echo 'int: ', $overflow->message, "\n";}
// The same sum as a `Core\BigInt`. This prints 9223372036854775808.echo Core\BigInt::of($largest)->plus(Core\BigInt::of(1)), "\n";
// There is no size at which this stops working. This prints// 9223372036854776807.echo Core\BigInt::of($largest)->plus(Core\BigInt::of(1000)), "\n";int: Integer addition overflowed92233720368547758089223372036854776807A running total
<?nvs// Shows a running total that grows too large for an `int`. Three jobs report the// number of bytes they wrote as text, and the program adds them up.
array<string> $written = [ '8070450532247928832', '8070450532247928832', '1152921504606846976',];
var $total = Core\BigInt::of(0);foreach ($written as string $bytes) { // Each report is read as a number and added to the total so far. `plus` // returns the new total, so the result is kept in `$total`. $total = $total->plus(Core\BigInt::parse($bytes));}
// The three numbers together are larger than an `int`. This prints// 17293822569102704640.echo $total, "\n";17293822569102704640