Ejemplo n.º 1
0
 public function testDiv()
 {
     $this->assertEquals(gmp_strval(gmp_div($this->a, $this->a)), $this->math->div($this->a, $this->a));
     $this->assertEquals(gmp_strval(gmp_div($this->b, $this->b)), $this->math->div($this->b, $this->b));
     $this->assertEquals(gmp_strval(gmp_div($this->c, $this->c)), $this->math->div($this->c, $this->c));
     $this->assertEquals(1, $this->math->div(1, 1));
 }
function GetAuthID($i64friendID)
{
    $tmpfriendID = $i64friendID;
    $iServer = "1";
    if (extension_loaded('bcmath') == 1) {
        //decode communityid with bcmath
        if (bcmod($i64friendID, "2") == "0") {
            $iServer = "0";
        }
        $tmpfriendID = bcsub($tmpfriendID, $iServer);
        if (bccomp("76561197960265728", $tmpfriendID) == -1) {
            $tmpfriendID = bcsub($tmpfriendID, "76561197960265728");
        }
        $tmpfriendID = bcdiv($tmpfriendID, "2");
        return "STEAM_0:" . $iServer . ":" . $tmpfriendID;
    } else {
        if (extension_loaded('gmp') == 1) {
            //decode communityid with gmp
            if (gmp_mod($i64friendID, "2") == "0") {
                $iServer = "0";
            }
            $tmpfriendID = gmp_sub($tmpfriendID, $iServer);
            if (gmp_cmp("76561197960265728", $tmpfriendID) == -1) {
                $tmpfriendID = gmp_sub($tmpfriendID, "76561197960265728");
            }
            $tmpfriendID = gmp_div($tmpfriendID, "2");
            return "STEAM_0:" . $iServer . ":" . gmp_strval($tmpfriendID);
        }
    }
    return false;
}
Ejemplo n.º 3
0
function gmp_shiftr($x, $n)
{
    if ($x < 0) {
        return gmp_strval(gmp_com(gmp_div(gmp_com($x), gmp_pow(2, $n))));
    } else {
        return gmp_strval(gmp_div($x, gmp_pow(2, $n)));
    }
}
Ejemplo n.º 4
0
 /**
  * {@inheritDoc}
  * @see \Mdanter\Ecc\RandomNumberGeneratorInterface::generate()
  */
 public function generate($max)
 {
     $random = gmp_strval(gmp_random());
     $small_rand = rand();
     while (gmp_cmp($random, $max) > 0) {
         $random = gmp_div($random, $small_rand, GMP_ROUND_ZERO);
     }
     return gmp_strval($random);
 }
Ejemplo n.º 5
0
 public function testdiv()
 {
     $a = 1234;
     $b = '1234123412341234123412341234123412412341234213412421341342342';
     $c = '0x1234123412341234123412341234123412412341234213412421341342342';
     $math = new GmpEngine();
     $this->assertEquals(gmp_strval(gmp_div($a, $a)), $math->div($a, $a));
     $this->assertEquals(gmp_strval(gmp_div($b, $b)), $math->div($b, $b));
     $this->assertEquals(gmp_strval(gmp_div($c, $c)), $math->div($c, $c));
     $this->assertEquals(1, $math->div(1, 1));
 }
Ejemplo n.º 6
0
 private function computeBaseNDigits($number, $targetBase)
 {
     $digits = array();
     $length = $this->computeBaseNLength($number, $targetBase);
     for ($i = 0; $i < $length; $i++) {
         $pow = gmp_pow($targetBase, $length - $i - 1);
         $div = gmp_div($number, $pow, GMP_ROUND_ZERO);
         $number = gmp_sub($number, gmp_mul($div, $pow));
         $digits[] = $div;
     }
     return array_map('gmp_strval', $digits);
 }
Ejemplo n.º 7
0
 /**
  * @dataProvider providerTestTAGLong
  */
 public function testPutTAGLong($value)
 {
     $fPtr = fopen($this->vFile->url(), 'wb');
     // 32-bit longs seem to be too long for pack() on 32-bit machines. Split into 4x16-bit instead.
     $quarters[0] = gmp_div(gmp_and($value, '0xFFFF000000000000'), gmp_pow(2, 48));
     $quarters[1] = gmp_div(gmp_and($value, '0x0000FFFF00000000'), gmp_pow(2, 32));
     $quarters[2] = gmp_div(gmp_and($value, '0x00000000FFFF0000'), gmp_pow(2, 16));
     $quarters[3] = gmp_and($value, '0xFFFF');
     $binary = pack('nnnn', gmp_intval($quarters[0]), gmp_intval($quarters[1]), gmp_intval($quarters[2]), gmp_intval($quarters[3]));
     $this->dataHandler->putTAGLong($fPtr, $value);
     $this->assertSame($binary, $this->vFile->getContent());
 }
Ejemplo n.º 8
0
 public static function gmp_random($n)
 {
     if (extension_loaded('gmp') && USE_EXT == 'GMP') {
         $random = gmp_strval(gmp_random());
         $small_rand = rand();
         while (gmp_cmp($random, $n) > 0) {
             $random = gmp_div($random, $small_rand, GMP_ROUND_ZERO);
         }
         return gmp_strval($random);
     } else {
         throw new Exception("PLEASE INSTALL GMP");
     }
 }
Ejemplo n.º 9
0
 /**
  * @param int $value
  *
  * @return string
  */
 public static function encode($value)
 {
     $value = gmp_init($value, 10);
     $octets = chr(gmp_strval(gmp_and($value, 0x7f), 10));
     $rightShift = function ($number, $positions) {
         return gmp_div($number, gmp_pow(2, $positions));
     };
     $value = $rightShift($value, 7);
     while (gmp_cmp($value, 0) > 0) {
         $octets .= chr(gmp_strval(gmp_or(0x80, gmp_and($value, 0x7f)), 10));
         $value = $rightShift($value, 7);
     }
     return strrev($octets);
 }
Ejemplo n.º 10
0
function Zend_OpenId_bigNumToBin2($bn)
{
    if (extension_loaded('gmp')) {
        /*The GMP conversion code in this function was liberally copied 
        	 and adapted from  JanRain's Auth_OpenId_MathLibrary::longToBinary*/
        $cmp = gmp_cmp($bn, 0);
        if ($cmp < 0) {
            throw new Zend_OpenId_Exception('Big integer arithmetic error', Zend_OpenId_Exception::ERROR_LONG_MATH);
        }
        if ($cmp == 0) {
            return "";
        }
        $bytes = array();
        while (gmp_cmp($bn, 0) > 0) {
            array_unshift($bytes, gmp_mod($bn, 256));
            $bn = gmp_div($bn, pow(2, 8));
        }
        if ($bytes && $bytes[0] > 127) {
            array_unshift($bytes, 0);
        }
        $string = '';
        foreach ($bytes as $byte) {
            $string .= pack('C', $byte);
        }
        return $string;
    } else {
        if (extension_loaded('bcmath')) {
            $cmp = bccomp($bn, 0);
            if ($cmp == 0) {
                return chr(0);
            } else {
                if ($cmp < 0) {
                    throw new Zend_OpenId_Exception('Big integer arithmetic error', Zend_OpenId_Exception::ERROR_LONG_MATH);
                }
            }
            $bin = "";
            while (bccomp($bn, 0) > 0) {
                $bin = chr(bcmod($bn, 256)) . $bin;
                $bn = bcdiv($bn, 256);
            }
            return $bin;
        }
    }
    throw new Zend_OpenId_Exception('The system doesn\'t have proper big integer extension', Zend_OpenId_Exception::UNSUPPORTED_LONG_MATH);
}
function recoverPubKey($r, $s, $e, $recoveryFlags, $G)
{
    $isYEven = ($recoveryFlags & 1) != 0;
    $isSecondKey = ($recoveryFlags & 2) != 0;
    $curve = $G->getCurve();
    $signature = new Signature($r, $s);
    // Precalculate (p + 1) / 4 where p is the field order
    static $p_over_four;
    // XXX just assuming only one curve/prime will be used
    if (!$p_over_four) {
        $p_over_four = gmp_div(gmp_add($curve->getPrime(), 1), 4);
    }
    // 1.1 Compute x
    if (!$isSecondKey) {
        $x = $r;
    } else {
        $x = gmp_add($r, $G->getOrder());
    }
    // 1.3 Convert x to point
    $alpha = gmp_mod(gmp_add(gmp_add(gmp_pow($x, 3), gmp_mul($curve->getA(), $x)), $curve->getB()), $curve->getPrime());
    $beta = NumberTheory::modular_exp($alpha, $p_over_four, $curve->getPrime());
    // If beta is even, but y isn't or vice versa, then convert it,
    // otherwise we're done and y == beta.
    if (isBignumEven($beta) == $isYEven) {
        $y = gmp_sub($curve->getPrime(), $beta);
    } else {
        $y = $beta;
    }
    // 1.4 Check that nR is at infinity (implicitly done in construtor)
    $R = new Point($curve, $x, $y, $G->getOrder());
    $point_negate = function ($p) {
        return new Point($p->curve, $p->x, gmp_neg($p->y), $p->order);
    };
    // 1.6.1 Compute a candidate public key Q = r^-1 (sR - eG)
    $rInv = NumberTheory::inverse_mod($r, $G->getOrder());
    $eGNeg = $point_negate(Point::mul($e, $G));
    $Q = Point::mul($rInv, Point::add(Point::mul($s, $R), $eGNeg));
    // 1.6.2 Test Q as a public key
    $Qk = new PublicKey($G, $Q);
    if ($Qk->verifies($e, $signature)) {
        return $Qk;
    }
    return false;
}
Ejemplo n.º 12
0
/**
 * Calculate Wang hash for 64bit unsigned integer using GMP library
 * PHP only supports signed integers even with 64bit version
 *
 * See <code/nel/include/nel/misc/wang_hash.h> on https://bitbucket.org/ryzom/ryzomcore
 *
 * @param string $key
 *
 * @return string hash
 */
function wang_hash64($key)
{
    // force $key to be base 10
    $key = gmp_init($key, 10);
    //$key = (~$key) + ($key << 21);
    $key = gmp_add(gmp_com($key), gmp_mul($key, 1 << 21));
    //$key = $key ^ ($key >> 24);
    $key = gmp_xor($key, gmp_div($key, 1 << 24));
    //$key = $key * 265;
    $key = gmp_mul($key, 265);
    //$key = $key ^ ($key >> 14);
    $key = gmp_xor($key, gmp_div($key, 1 << 14));
    //$key = $key * 21;
    $key = gmp_mul($key, 21);
    //$key = $key ^ ($key >> 28);
    $key = gmp_xor($key, gmp_div($key, 1 << 28));
    //$key = $key + ($key << 31);
    $key = gmp_add($key, gmp_mul($key, gmp_pow(2, 31)));
    // limit to 64bit
    $key = gmp_and($key, "0xFFFFFFFFFFFFFFFF");
    return gmp_strval($key, 10);
}
Ejemplo n.º 13
0
 public static function int_to_string($x)
 {
     if (extension_loaded('gmp') && USE_EXT == 'GMP') {
         if (gmp_cmp($x, 0) >= 0) {
             if (gmp_cmp($x, 0) == 0) {
                 return chr(0);
             }
             $result = "";
             while (gmp_cmp($x, 0) > 0) {
                 $q = gmp_div($x, 256, 0);
                 $r = gmp_Utils::gmp_mod2($x, 256);
                 $ascii = chr($r);
                 $result = $ascii . $result;
                 $x = $q;
             }
             return $result;
         }
     } else {
         if (extension_loaded('bcmath') && USE_EXT == 'BCMATH') {
             if (bccomp($x, 0) != -1) {
                 if (bccomp($x, 0) == 0) {
                     return chr(0);
                 }
                 $result = "";
                 while (bccomp($x, 0) == 1) {
                     $q = bcdiv($x, 256, 0);
                     $r = bcmod($x, 256);
                     $ascii = chr($r);
                     $result = $ascii . $result;
                     $x = $q;
                 }
                 return $result;
             }
         } else {
             throw new ErrorException("Please install BCMATH or GMP");
         }
     }
 }
Ejemplo n.º 14
0
 public static function leftmost_bit($x)
 {
     if (extension_loaded('gmp') && USE_EXT == 'GMP') {
         if (gmp_cmp($x, 0) > 0) {
             $result = 1;
             while (gmp_cmp($result, $x) < 0 || gmp_cmp($result, $x) == 0) {
                 $result = gmp_mul(2, $result);
             }
             return gmp_strval(gmp_div($result, 2));
         }
     } else {
         throw new ErrorException("Please install GMP");
     }
 }
Ejemplo n.º 15
0
 /**
  * Returns part of number $num, starting at bit
  * position $start with length $length
  *
  * @param gmp resource $num
  * @param int start
  * @param int length
  * @return gmp resource
  * @access public
  */
 function subint($num, $start, $length)
 {
     $start_byte = intval($start / 8);
     $start_bit = $start % 8;
     $byte_length = intval($length / 8);
     $bit_length = $length % 8;
     if ($bit_length) {
         $byte_length++;
     }
     $num = gmp_div($num, 1 << $start_bit);
     $tmp = _byte_substr($this->int2bin($num), $start_byte, $byte_length);
     $tmp = str_pad($tmp, $byte_length, "");
     $tmp = _byte_substr_replace($tmp, $tmp[$byte_length - 1] & _byte_chr(0xff >> 8 - $bit_length), $byte_length - 1, 1);
     return $this->bin2int($tmp);
 }
Ejemplo n.º 16
0
 /**
  * Divide numbers
  *
  * @param mixed $number
  * @access public
  * @return self
  */
 public function div($number)
 {
     $result = gmp_div($this->getRawValue(), static::upgradeParam($number)->getRawValue(), GMP_ROUND_ZERO);
     return static::factory($result);
 }
Ejemplo n.º 17
0
function gmp_shiftr($x, $n)
{
    return gmp_div($x, gmp_pow(2, $n));
}
Ejemplo n.º 18
0
 /**
  * Read Windows FileTime and convert to Unix timestamp
  * Filetime = 64-bit value with the number of 100-nsec intervals since Jan 1, 1601 (UTC)
  * Based on http://www.mysqlperformanceblog.com/2007/03/27/integers-in-php-running-with-scissors-and-portability/
  * @return Unix timestamp, or -1 on error
  */
 private function readFiletime()
 {
     // Unix epoch (1970-01-01) - Windows epoch (1601-01-01) in 100ns units
     $EPOCHDIFF = '116444735995904000';
     $UINT32MAX = '4294967296';
     $USEC2SEC = 1000000;
     $lo = $this->readInt32();
     $hi = $this->readInt32();
     // check for 64-bit platform
     if (PHP_INT_SIZE >= 8) {
         // use native math
         if ($lo < 0) {
             $lo += 1 << 32;
         }
         $date = ($hi << 32) + $lo;
         $this->debugLog(sprintf('PAK CreationDate source: %016x', $date));
         if ($date == 0) {
             return -1;
         }
         // convert to Unix timestamp in usec
         $stamp = ($date - (int) $EPOCHDIFF) / 10;
         $this->debugLog(sprintf('PAK CreationDate 64-bit: %u.%06u', $stamp / $USEC2SEC, $stamp % $USEC2SEC));
         return (int) ($stamp / $USEC2SEC);
         // check for 32-bit platform
     } elseif (PHP_INT_SIZE >= 4) {
         $this->debugLog(sprintf('PAK CreationDate source: %08x%08x', $hi, $lo));
         if ($lo == 0 && $hi == 0) {
             return -1;
         }
         // workaround signed/unsigned braindamage on x32
         $lo = sprintf('%u', $lo);
         $hi = sprintf('%u', $hi);
         // try and use GMP
         if (function_exists('gmp_mul')) {
             $date = gmp_add(gmp_mul($hi, $UINT32MAX), $lo);
             // convert to Unix timestamp in usec
             $stamp = gmp_div(gmp_sub($date, $EPOCHDIFF), 10);
             $stamp = gmp_div_qr($stamp, $USEC2SEC);
             $this->debugLog(sprintf('PAK CreationDate GNU MP: %u.%06u', gmp_strval($stamp[0]), gmp_strval($stamp[1])));
             return (int) gmp_strval($stamp[0]);
         }
         // try and use BC Math
         if (function_exists('bcmul')) {
             $date = bcadd(bcmul($hi, $UINT32MAX), $lo);
             // convert to Unix timestamp in usec
             $stamp = bcdiv(bcsub($date, $EPOCHDIFF), 10, 0);
             $this->debugLog(sprintf('PAK CreationDate BCMath: %u.%06u', bcdiv($stamp, $USEC2SEC), bcmod($stamp, $USEC2SEC)));
             return (int) bcdiv($stamp, $USEC2SEC);
         }
         // compute everything manually
         $a = substr($hi, 0, -5);
         $b = substr($hi, -5);
         // hope that float precision is enough
         $ac = $a * 42949;
         $bd = $b * 67296;
         $adbc = $a * 67296 + $b * 42949;
         $r4 = substr($bd, -5) + substr($lo, -5);
         $r3 = substr($bd, 0, -5) + substr($adbc, -5) + substr($lo, 0, -5);
         $r2 = substr($adbc, 0, -5) + substr($ac, -5);
         $r1 = substr($ac, 0, -5);
         while ($r4 >= 100000) {
             $r4 -= 100000;
             $r3++;
         }
         while ($r3 >= 100000) {
             $r3 -= 100000;
             $r2++;
         }
         while ($r2 >= 100000) {
             $r2 -= 100000;
             $r1++;
         }
         $date = ltrim(sprintf('%d%05d%05d%05d', $r1, $r2, $r3, $r4), '0');
         // convert to Unix timestamp in usec
         $r3 = substr($date, -6) - substr($EPOCHDIFF, -6);
         $r2 = substr($date, -12, 6) - substr($EPOCHDIFF, -12, 6);
         $r1 = substr($date, -18, 6) - substr($EPOCHDIFF, -18, 6);
         if ($r3 < 0) {
             $r3 += 1000000;
             $r2--;
         }
         if ($r2 < 0) {
             $r2 += 1000000;
             $r1--;
         }
         $stamp = substr(sprintf('%d%06d%06d', $r1, $r2, $r3), 0, -1);
         $this->debugLog(sprintf('PAK CreationDate manual: %s.%s', substr($stamp, 0, -6), substr($stamp, -6)));
         return (int) substr($stamp, 0, -6);
     } else {
         return -1;
     }
 }
 public static function gmp_dec2base($dec, $base, $digits = FALSE)
 {
     if (extension_loaded('gmp')) {
         if ($base < 2 or $base > 256) {
             die("Invalid Base: " . $base);
         }
         $value = "";
         if (!$digits) {
             $digits = self::digits($base);
         }
         $dec = gmp_init($dec);
         $base = gmp_init($base);
         while (gmp_cmp($dec, gmp_sub($base, '1')) > 0) {
             $rest = gmp_mod($dec, $base);
             $dec = gmp_div($dec, $base);
             $value = $digits[gmp_intval($rest)] . $value;
         }
         $value = $digits[gmp_intval($dec)] . $value;
         return (string) $value;
     } else {
         throw new ErrorException("Please install GMP");
     }
 }
Ejemplo n.º 20
0
 /**
  * Return the number of not ordered, none repetitive combination of size [$combinationSize] existing in [$itemCount] elements
  *
  * If GMP is installed, GMP will be used to compute this value,
  * If libbcmath is installed, bcmath will be used for all mathematics operation.
  *
  * If none of previous library is available, then basic php functions will be used,
  * so the function could result in an error or php can return INF.
  *
  * If GMP is not installed, be aware of the "Maximum function nesting level" value.
  *
  * @param int $itemCount       The number of possible element
  * @param int $combinationSize The size of each combination
  *
  * @return int The number of combination
  *
  * @throws \InvalidArgumentException If [$itemCount] < 0 or [$combinationSize] > [$itemCount]
  */
 public static function getCombinationCount($itemCount, $combinationSize)
 {
     if (function_exists('gmp_mul') && function_exists('gmp_div')) {
         return gmp_strval(gmp_div(self::factorial($itemCount), gmp_mul(self::factorial($combinationSize), self::factorial($itemCount - $combinationSize))));
     } elseif (function_exists('bcmul') && function_exists('bcdiv')) {
         return bcdiv(self::factorial($itemCount), bcmul(self::factorial($combinationSize), self::factorial($itemCount - $combinationSize)));
     }
     return self::factorial($itemCount) / (self::factorial($combinationSize) * self::factorial($itemCount - $combinationSize));
 }
Ejemplo n.º 21
0
 public static function ShiftRight($Number, $Bits)
 {
     //return bcdiv($Number, bcpow('2', $Bits));
     return gmp_div($Number, gmp_pow(2, $Bits));
 }
Ejemplo n.º 22
0
 public static function leftmost_bit($x)
 {
     if (gmp_cmp($x, 0) > 0) {
         $result = 1;
         while (gmp_cmp($result, $x) <= 0) {
             $result = gmp_mul(2, $result);
         }
         return gmp_div($result, 2);
     }
 }
Ejemplo n.º 23
0
 /**
  * Divide two integers, utilize Math extensions
  *
  * @param mixed a First operand
  * @param mixed b Second operand
  * @return mixed
  * @access private
  */
 function _div($a, $b)
 {
     switch (MATH_BASEX_MATHEXTENSION) {
         case 'bcmath':
             return bcdiv($a, $b);
         case 'gmp':
             return gmp_strval(gmp_div($a, $b));
         case 'none':
             return floor($a / $b);
     }
 }
Ejemplo n.º 24
0
 public function parse(DateTimeParseContext $context, $text, $position)
 {
     $length = strlen($text);
     if ($position === $length) {
         return ~$position;
     }
     if ($position < 0 || $position >= $length) {
         throw new \OutOfRangeException();
     }
     $sign = $text[$position];
     $negative = false;
     $positive = false;
     if ($sign === $context->getDecimalStyle()->getPositiveSign()) {
         if ($this->signStyle->parse(true, $context->isStrict(), $this->minWidth === $this->maxWidth) === false) {
             return ~$position;
         }
         $positive = true;
         $position++;
     } else {
         if ($sign === $context->getDecimalStyle()->getNegativeSign()) {
             if ($this->signStyle->parse(false, $context->isStrict(), $this->minWidth === $this->maxWidth) === false) {
                 return ~$position;
             }
             $negative = true;
             $position++;
         } else {
             if ($this->signStyle == SignStyle::ALWAYS() && $context->isStrict()) {
                 return ~$position;
             }
         }
     }
     $effMinWidth = $context->isStrict() || $this->isFixedWidth($context) ? $this->minWidth : 1;
     $minEndPos = $position + $effMinWidth;
     if ($minEndPos > $length) {
         return ~$position;
     }
     $effMaxWidth = ($context->isStrict() || $this->isFixedWidth($context) ? $this->maxWidth : 9) + Math::max($this->subsequentWidth, 0);
     $total = 0;
     $totalBig = null;
     $pos = $position;
     for ($pass = 0; $pass < 2; $pass++) {
         $maxEndPos = Math::min($pos + $effMaxWidth, $length);
         while ($pos < $maxEndPos) {
             $ch = $text[$pos++];
             $digit = $context->getDecimalStyle()->convertToDigit($ch);
             if ($digit < 0) {
                 $pos--;
                 if ($pos < $minEndPos) {
                     return ~$position;
                     // need at least min width digits
                 }
                 break;
             }
             if ($pos - $position > 18) {
                 if ($totalBig === null) {
                     $totalBig = \gmp_init($total);
                 }
                 $totalBig = \gmp_add(\gmp_mul($totalBig, "10"), \gmp_init($digit));
             } else {
                 $total = $total * 10 + $digit;
             }
         }
         if ($this->subsequentWidth > 0 && $pass === 0) {
             // re-parse now we know the correct width
             $parseLen = $pos - $position;
             $effMaxWidth = Math::max($effMinWidth, $parseLen - $this->subsequentWidth);
             $pos = $position;
             $total = 0;
             $totalBig = null;
         } else {
             break;
         }
     }
     if ($negative) {
         if ($totalBig !== null) {
             if (\gmp_cmp($totalBig, "0") === 0 && $context->isStrict()) {
                 return ~($position - 1);
                 // minus zero not allowed
             }
             $totalBig = \gmp_neg($totalBig);
         } else {
             if ($total === 0 && $context->isStrict()) {
                 return ~($position - 1);
                 // minus zero not allowed
             }
             $total = -$total;
         }
     } else {
         if ($this->signStyle == SignStyle::EXCEEDS_PAD() && $context->isStrict()) {
             $parseLen = $pos - $position;
             if ($positive) {
                 if ($parseLen <= $this->minWidth) {
                     return ~($position - 1);
                     // '+' only parsed if minWidth exceeded
                 }
             } else {
                 if ($parseLen > $this->minWidth) {
                     return ~$position;
                     // '+' must be parsed if minWidth exceeded
                 }
             }
         }
     }
     if ($totalBig !== null) {
         if (gmp_cmp($totalBig, "-9223372036854775808") < 0 || gmp_cmp($totalBig, "9223372036854775807") > 0) {
             // overflow, parse 1 less digit
             $totalBig = gmp_div($totalBig, "10");
             $pos--;
         }
         return $this->setValue($context, gmp_intval($totalBig), $position, $pos);
     }
     return $this->setValue($context, $total, $position, $pos);
 }
 public static function gmp_squareRootModP($prime, $verbose = false)
 {
     $start_time = microtime(true);
     if ($verbose) {
         echo "Testing primes for modulus " . $prime . "<br />";
     }
     $squares = array();
     for ($root = 0; gmp_cmp($root, gmp_add(1, gmp_div($prime, 2))) < 0; $root = gmp_add($root, 1)) {
         $sq = gmp_strval(gmp_powm($root, 2, $prime));
         $calculated = NumberTheory::square_root_mod_prime($sq, $prime);
         $calc_sq = gmp_strval(gmp_powm($calculated, 2, $prime));
         if (gmp_cmp($calculated, $root) != 0 && gmp_cmp(gmp_sub($prime, $calculated), $root) != 0) {
             $error_tally++;
             echo "FAILED TO FIND " . gmp_strval($root) . " AS sqrt(" . gmp_strval($sq) . ") mod {$prime} . Said {$calculated} (" . ($prime - $calculated) . ") <br />\n";
             flush();
         } else {
             if ($verbose) {
                 echo "SUCCESS TO FIND " . gmp_strval($root) . " AS sqrt(" . gmp_strval($sq) . ") mod {$prime} . Said {$calculated} (" . ($prime - $calculated) . ") <br />\n";
             }
             flush();
         }
     }
     $end_time = microtime(true);
     $time_res = $end_time - $start_time;
     echo "<br />Square roots mod " . $prime . " took: " . $time_res . " seconds. <br />";
 }
Ejemplo n.º 26
0
$div3 = gmp_div_q("1", "3", GMP_ROUND_PLUSINF);
echo gmp_strval($div3) . "\n";
$div4 = gmp_div_q("-1", "4", GMP_ROUND_PLUSINF);
echo gmp_strval($div4) . "\n";
$div5 = gmp_div_q("-1", "4", GMP_ROUND_MINUSINF);
echo gmp_strval($div5) . "\n";
// gmp_div_qr
$a = gmp_init("0x41682179fbf5");
$res = gmp_div_qr($a, "0xDEFE75");
var_dump($res);
printf("Result is: q - %s, r - %s" . PHP_EOL, gmp_strval($res[0]), gmp_strval($res[1]));
// gmp_div_r
$div = gmp_div_r("105", "20");
echo gmp_strval($div) . "\n";
// gmp_div
$div1 = gmp_div("100", "5");
echo gmp_strval($div1) . "\n";
// gmp_divexact
$div1 = gmp_divexact("10", "2");
echo gmp_strval($div1) . "\n";
// gmp_fact
$fact1 = gmp_fact(5);
// 5 * 4 * 3 * 2 * 1
echo gmp_strval($fact1) . "\n";
$fact2 = gmp_fact(50);
// 50 * 49 * 48, ... etc
echo gmp_strval($fact2) . "\n";
// gmp_gcd
$gcd = gmp_gcd("12", "21");
echo gmp_strval($gcd) . "\n";
// gmp_gcdext
Ejemplo n.º 27
0
 /**
  * Divide two big integers and return result or NULL if the denominator
  * is zero.
  * @param string $left_operand
  * @param string $right_operand
  * @return string|null
  */
 public function divide($left_operand, $right_operand)
 {
     $result = gmp_div($left_operand, $right_operand);
     return gmp_strval($result);
 }
Ejemplo n.º 28
0
function get_ipv6_64_html($ip = 0, $zoom = 2, $row_height)
{
    global $conf, $self, $onadb, $color, $style, $images;
    $html = '';
    if ($ip == 0) {
        return $html;
    }
    $ips_per_block = gmp_init("18446744073709551615");
    $ip_end = gmp_add(gmp_init($ip), $ips_per_block);
    $display_factor = gmp_div($ips_per_block, "255");
    $x_px_per_ip = $zoom;
    // Select all subnet records
    //$where = "ip_addr >= {$ip} AND ip_addr <= " . $ona->qstr($ip_end);
    $where = "ip_addr >= {$ip} AND ip_addr <= " . gmp_strval($ip_end);
    list($status, $num_subnets, $subnets) = db_get_records($onadb, 'subnets', $where, "ip_addr ASC");
    // If the first record isn't a subnet, see if the first IP is in another subnet
    if ($num_subnets > 0 && gmp_cmp(gmp_init($subnets[0]['ip_addr']), $ip) != 0) {
        $where = "ip_addr < {$ip} AND ((340282366920938463463374607431768211454 - ip_mask) + ip_addr) >= {$ip} AND ip_mask > 4294967296";
        list($status, $rows, $temp_subnet) = db_get_record($onadb, 'subnets', $where);
        if ($rows) {
            $num_subnets++;
            array_unshift($subnets, $temp_subnet);
        }
    }
    $block_start = gmp_init($ip);
    // Find the next block of addresses
    while (gmp_cmp($block_start, $ip_end) < 0) {
        if (!is_array($subnet) or gmp_cmp($block_start, $subnet['ip_addr']) > 0) {
            $subnet = array_shift($subnets);
            if (is_array($subnet)) {
                $subnet['SIZE'] = gmp_add(gmp_sub(gmp_init("0xffffffffffffffffffffffffffffffff"), $subnet['ip_mask']), "1");
                $subnet['ip_addr_end'] = gmp_sub(gmp_add(gmp_init($subnet['ip_addr']), $subnet['SIZE']), "1");
                $subnet['ip_addr'] = gmp_init($subnet['ip_addr']);
            } else {
                // pretend like the next subnet record is the next /64
                $subnet['SIZE'] = gmp_add(gmp_sub($ip_end, "{$block_start}"), "1");
                $subnet['ip_addr'] = gmp_add($ip_end, "1");
            }
        }
        // If it's unallocated space
        if (gmp_cmp($block_start, $subnet['ip_addr']) < 0) {
            $block_end = gmp_sub($subnet['ip_addr'], "1");
            $block_color = $color['bgcolor_map_empty'];
        } else {
            $block_end = $subnet['ip_addr_end'];
            if (gmp_cmp($block_end, $ip_end) > 0) {
                $block_end = $ip_end;
            }
            $block_color = $color['bgcolor_map_subnet'];
        }
        $block_size = gmp_add(gmp_sub($block_end, $block_start), "1");
        // $block_size_total += $block_size;
        // $block_title = htmlentities($subnet['DESCRIPTION'] . " :: Size={$block_size}", ENT_QUOTES) . ' :: ' . ip_mangle($block_start, 'dotted') . " -> " . ip_mangle($block_end, 'dotted');
        // Display the current block (-1 for px border unless it's IE)
        $x = gmp_sub(gmp_div(gmp_mul($block_size, "{$x_px_per_ip}"), $display_factor), "1");
        if (strpos($_SERVER['HTTP_USER_AGENT'], 'MSIE') != false) {
            $x = gmp_add($x, "1");
        }
        $str_block_start = gmp_strval($block_start);
        $str_x = gmp_strval($x);
        $html .= <<<EOL
<div id="{$str_block_start}_block"
     style="
       clear: none; float: left;
       border-right: 1px solid #000000; background-color: {$block_color};
       width: {$str_x}px; height: {$row_height}px;"
     onMouseOver="
       wwTT(this, event,
         'id', 'tt_subnet_{$str_block_start}',
         'type', 'velcro',
         'styleClass', 'wwTT_niceTitle',
         'direction', 'south',
         'javascript', 'xajax_window_submit(\\'tooltips\\', \\'tooltip=>subnet,id=>tt_subnet_{$str_block_start},subnet_ip=>{$str_block_start}\\');'
       );"
></div>
EOL;
        $block_start = gmp_add($block_end, "1");
    }
    return $html;
}
Ejemplo n.º 29
0
function commission($amount, $percentage, $cap = false, $already_paid = '0')
{
    $commission = gmp_div(gmp_mul((string) $amount, numstr_to_internal((string) $percentage)), numstr_to_internal(100));
    // reduce the cap by the amount we already paid, but no lower than 0
    if (!$cap) {
        return gmp_strval($commission);
    }
    $cap = max(gmp_strval(gmp_sub(numstr_to_internal($cap), $already_paid)), '0');
    return min(gmp_strval($commission), $cap);
}
 /**
  * Divide two Math_Integer objects: $i1 / $i2
  *
  * @param object Math_Integer $int1
  * @param object Math_Integer $int2
  * @return object Math_Integer on success, PEAR_Error otherwise
  * @access public
  */
 function &div(&$int1, &$int2)
 {
     /*{{{*/
     if (PEAR::isError($err = Math_IntegerOp::_validInts($int1, $int2))) {
         return $err;
     }
     switch (MATH_INTLIB) {
         /*{{{*/
         case 'gmp':
             $tmp = gmp_strval(gmp_div($int1->getValue(), $int2->getValue()));
             break;
         case 'bcmath':
             $tmp = bcdiv($int1->getValue(), $int2->getValue());
             break;
         case 'std':
             $tmp = intval($int1->getValue() / $int2->getValue());
             break;
     }
     /*}}}*/
     return new Math_Integer($tmp);
 }