"Share" PHP int large overflow integer plus and minus operation function, if there is a better way to welcome the discussion

Source: Internet
Author: User
Tags bitwise gmp
PHP overflow plus minus operation Super Large integer

Share an arithmetic function that overflows integer addition and subtraction, just write, for overflow integer can use this to add and subtract operation.
The points of regret are:
One code too many, two only has the addition and subtraction operation, the multiplication not to take the surplus;



In fact, there is a more convenient way is to use SQL database: SELECT n1+n2;
mysql> SELECT 11234123413241341234123412341234+1;+------------------------------------+| 11234123413241341234123412341234+1 |+------------------------------------+|   11234123413241341234123412341235 |+------------------------------------+1 row in Set (0.00 sec) Mysql> SELECT 11234123413241341234123412341234*12341234123;+----------------------------------------------+| 11234123413241341234123412341234*12341234123 |+----------------------------------------------+|   138642947209487270472850788378836360727782 |+----------------------------------------------+1 row in Set (0.00 sec)


If there is a better way, please feel free to reply or send a message to me. Welcome to explore.

/* big int operate [by FUZB 20130826] */function biginto ($num 1, $op, $num 2) {$arr = array ();    $endop = ";    $num 1o = $num 1;    $num 2o = $num 2;        if ($num 1 < 0) {$c 1 =-1;    $num 1 = preg_replace ('/^ (-)/', ' ', $num 1);    } else {$c 1 = 1;        } if ($num 2 < 0) {$c 2 =-1;    $num 2 = preg_replace ('/^ (-)/', ' ', $num 2);    } else {$c 2 = 1;    } $len 1 = strlen ($num 1);    $len 2 = strlen ($num 2);    $len = Max (strlen ($num 1), strlen ($num 2));    if ($len 1 < $len) $num 1 = str_pad (' 0 ', $len-$len 1). $num 1;    if ($len 2 < $len) $num 2 = Str_pad (' 0 ', $len-$len 2). $num 2; if ($op = = ' + ') {if ($c 1 = = $c 2) {$endop = $c 1 > 0?        '':'-';            } else {$endop = ABS ($num 1o) > abs ($num 2o)? $c 1: $c 2; $endop = $ENDOP > 0?        '':'-'; } $CC = $endop = = '-'?        -1:1;            for ($i =0; $i < $len; $i + +) {$n 1 = intval ($num 1{$i});       $n 2 = intval ($num 2{$i});     $n = $n 1* $c 1+ $n $c 2;        $arr [$i] = $n * $CC; }} else if ($op = = '-') {if ($c 1 < 0) {$endop = $c 2 > 0? '-':(abs ($num 1o) > abs ($num 2o)?        '-':''); } else {$endop = $c 2 > 0? (ABS ($num 1o) > abs ($num 2o)?        '':'-'):''; } $CC = $endop = = '-'?        -1:1;            for ($i =0; $i < $len; $i + +) {$n 1 = intval ($num 1{$i});            $n 2 = intval ($num 2{$i});            $n = $n 1* $c 1-$n $c 2;        $arr [$i] = $n * $CC;    }} $len = count ($arr);    $arr 2 = array ();            for ($i =0; $i < $len; $i + +) {if ($arr [$i] < 0) {$n = $arr [$i] + 10;            $arr 2[$i] = $n;            $j = $i-1;                    while (true) {if ($arr 2[$j] = = 0) {$arr 2[$j] = 9;                $j--;                    } else {$arr 2[$j]--;                Break }}} and else if ($arr [$I] > 9) {$n = $arr [$i]-10;            $arr 2[$i] = $n;            $j = $i-1;                    while (true) {if ($arr 2[$j] = = 9) {$arr 2[$j] = 0;                $j--;                    } else {$arr 2[$j]++;                Break        }}} else {$arr 2[$i] = $arr [$i];    }} $value = $endop. Preg_replace ('/^ (0{1,})/', ', implode ($arr 2)); return strlen ($value) > 0? $value: ' 0 ';}




Test:
$a = ' -12345678901234567890123456789 '; $b = ' 1 '; $c = Biginto ($a, ' + ', $b); Var_dump ($a); Var_dump ($b); Var_dump ($c); exit ();/* Output: String ' -12345678901234567890123456789 ' (length=30) string ' 1 ' (length=1) string '- 12345678901234567890123456788 ' (length=30) */


Reply to discussion (solution)

PHP has a library of two high-precision mathematical operations functions, BC and GMP

bcadd? ADD arbitrary precision Numbersbccomp? Compare arbitrary precision Numbersbcdiv? Divide arbitrary precision Numbersbcmod? Get modulus of an arbitrary precision Numberbcmul? Multiply arbitrary precision Numberbcpow? Raise an arbitrary precision number to anotherbcpowmod? Raise an arbitrary precision number to another, reduced by a specified modulusbcscale? Set Default scale parameter-all BC math functionsbcsqrt? Get the square root of an arbitrary precision numberbcsub? Subtract one arbitrary precision number from another 
Gmp_abs? Absolute Valuegmp_add? Add Numbersgmp_and? Bitwise andgmp_clrbit? Clear bitgmp_cmp? Compare numbersgmp_com? Calculates one ' s complementgmp_div_q? Divide NUMBERSGMP_DIV_QR? Divide numbers and get quotient and remaindergmp_div_r? Remainder of the division of Numbersgmp_div? Alias Gmp_div_qgmp_divexact? Exact Division of Numbersgmp_fact? Factorialgmp_gcd? Calculate Gcdgmp_gcdext? Calculate GCD and Multipliersgmp_hamdist? Hamming distancegmp_init? Create GMP numbergmp_intval? Convert GMP number to Integergmp_invert? Inverse by Modulogmp_jacobi? Jacobi Symbolgmp_legendre? Legendre symbolgmp_mod? Modulo Operationgmp_mul? Multiply Numbersgmp_neg? Negate numbergmp_nextprime? Find Next prime numbergmp_or? Bitwise Orgmp_perfect_square? Perfect Square Checkgmp_popcount? Population Countgmp_pow? Raise number into POWERGMP_POWM? Raise number into power with modulogmp_prob_prime? Check If number is "probably prime" Gmp_random? Random numbergmp_scan0? Scan for 0gmP_scan1? Scan for 1gmp_setbit? Set bitgmp_sign? Sign of numbergmp_sqrt? Calculate Square Rootgmp_sqrtrem? Square root with Remaindergmp_strval? Convert GMP number to stringgmp_sub? Subtract numbersgmp_testbit? Tests If a bit is Setgmp_xor? Bitwise XOR
  • Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.