当前位置: 首页>>代码示例>>PHP>>正文


PHP intdiv函数代码示例

本文整理汇总了PHP中intdiv函数的典型用法代码示例。如果您正苦于以下问题:PHP intdiv函数的具体用法?PHP intdiv怎么用?PHP intdiv使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。


在下文中一共展示了intdiv函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的PHP代码示例。

示例1: extendedGCD

 /**
  * Extended greatest common divisor
  * Compute the gcd as a multiple of the inputs:
  * gcd(a, b) = a*a' + b*b'
  * https://en.wikipedia.org/wiki/Extended_Euclidean_algorithm
  * Knuth, The Art of Computer Programming, Volume 2, 4.5.2 Algorithm X.
  *
  * @param  int $a
  * @param  int $b
  *
  * @return array [gcd, a', b']
  */
 public static function extendedGCD(int $a, int $b) : array
 {
     // Base cases
     if ($a == 0) {
         return [$b, 0, 1];
     }
     if ($b == 0) {
         return [$a, 1, 0];
     }
     $x₂ = 1;
     $x₁ = 0;
     $y₂ = 0;
     $y₁ = 1;
     while ($b > 0) {
         $q = intdiv($a, $b);
         $r = $a % $b;
         $x = $x₂ - $q * $x₁;
         $y = $y₂ - $q * $y₁;
         $x₂ = $x₁;
         $x₁ = $x;
         $y₂ = $y₁;
         $y₁ = $y;
         $a = $b;
         $b = $r;
     }
     return [$a, $x₂, $y₂];
 }
开发者ID:markrogoyski,项目名称:math-php,代码行数:39,代码来源:Algebra.php

示例2: main

function main()
{
    include_once 'numbers.php';
    $numbers = listToArray($numberList);
    $digitCount = count($numbers[0]);
    $numberCount = count($numbers);
    $realSum = [];
    $startUnit = 0;
    /**
     * This use the elementary sum method from right to left.
     */
    for ($i = $digitCount - 1; $i >= 0; $i--) {
        $sum = 0;
        for ($j = 0; $j < $numberCount; $j++) {
            $sum += intval($numbers[$j][$i]);
        }
        $sumSplit = array_reverse(str_split(strval($sum)));
        for ($k = 0; $k < count($sumSplit); $k++) {
            // NOTE: This null coalesce (??) only works on PHP 7
            $realSum[$startUnit + $k] = $realSum[$startUnit + $k] ?? 0;
            // Get the sum by column
            $colSum = $realSum[$startUnit + $k] + intval($sumSplit[$k]);
            // Put remainder to the current result column
            $realSum[$startUnit + $k] = $colSum % 10;
            // If the column sum is >= 10, put the carry number to the next result column
            if ($colSum >= 10) {
                $realSum[$startUnit + $k + 1] = $realSum[$startUnit + $k + 1] ?? 0;
                // NOTE: This intdiv() is also only on PHP 7
                $realSum[$startUnit + $k + 1] += intdiv($colSum, 10);
            }
        }
        $startUnit++;
    }
    var_dump(implode(array_reverse($realSum)));
}
开发者ID:ngocphamm,项目名称:ProjectEuler-Solutions-PHP,代码行数:35,代码来源:prob13.php

示例3: floorDiv

 /**
  * Returns the largest integer value that is less than or equal to the algebraic quotient.
  *
  * @param integer $a The first argument, validated as an integer.
  * @param integer $b The second argument, validated as a non-zero integer.
  *
  * @return integer
  */
 public static function floorDiv($a, $b)
 {
     $r = intdiv($a, $b);
     // If the signs are different and modulo not zero, round down.
     if (($a ^ $b) < 0 && $r * $b != $a) {
         $r--;
     }
     return $r;
 }
开发者ID:brick,项目名称:date-time,代码行数:17,代码来源:Math.php

示例4: quotient

 /** @return int */
 public final function quotient()
 {
     if (!function_exists('intdiv')) {
         // This method isn't actually used internally by the library
         // currently so no hard dependency on these polyfills.
         // @codeCoverageIgnoreStart
         throw new \LogicException(sprintf('%s() requires the intdiv() function which was added in PHP 7' . ' you could use a polyfill such as michaelc/intdiv-compat or' . ' symfony/polyfill-php70 to provide this function', __METHOD__));
         // @codeCoverageIgnoreEnd
     }
     return intdiv($this->result, $this->divisor);
 }
开发者ID:cs278,项目名称:bank-modulus,代码行数:12,代码来源:BaseAlgorithm.php

示例5: lyn_convertToMinutes

function lyn_convertToMinutes($seconds)
{
    $sec = $seconds % 60;
    if (function_exists('intdiv')) {
        $min = intdiv($seconds, 60);
    } else {
        $min = ($seconds - $sec) / 60;
    }
    $sec = abs($sec);
    $sec = $sec < 10 ? '0' . $sec : $sec;
    return "{$min}:{$sec}";
}
开发者ID:asccharania,项目名称:learning,代码行数:12,代码来源:custom.php

示例6: getTweets

 /**
  * @param TweetCriteria $criteria
  * @return Tweet[]
  */
 public function getTweets(TweetCriteria $criteria)
 {
     $results = array();
     try {
         $refreshCursor = null;
         if ($criteria->getMaxTweets() == 0) {
             return $results;
         }
         do {
             $response = $this->getUrlResponse($criteria->getUsername(), $criteria->getSince(), $criteria->getUntil(), $criteria->getQuerySearch(), $refreshCursor);
             $refreshCursor = $response['min_position'];
             $htmlCrawler = new Crawler($response['items_html']);
             $tweetsCrawler = $htmlCrawler->filter('div.js-stream-tweet');
             if ($tweetsCrawler->count() == 0) {
                 break;
             }
             $tweetsCrawler->each(function ($tweet) use(&$results) {
                 /** @var $tweet \Symfony\Component\DomCrawler\Crawler */
                 $username = $tweet->filter('span.username.js-action-profile-name b')->first()->text();
                 $text = str_replace('[^\\u0000-\\uFFFF]', '', $tweet->filter('p.js-tweet-text')->first()->text());
                 $retweets = intval(str_replace(',', '', $tweet->filter('span.ProfileTweet-action--retweet span.ProfileTweet-actionCount')->first()->attr('data-tweet-stat-count')));
                 $favorites = intval(str_replace(',', '', $tweet->filter('span.ProfileTweet-action--favorite span.ProfileTweet-actionCount')->first()->attr('data-tweet-stat-count')));
                 $date = new \DateTime('@' . intdiv(intval($tweet->filter('small.time span.js-short-timestamp')->first()->attr('data-time-ms')), 1000));
                 $id = $tweet->first()->attr('data-tweet-id');
                 $permalink = $tweet->first()->attr('data-permalink-path');
                 preg_match("(@\\w*)", $text, $mentions);
                 preg_match("(#\\w*)", $text, $hashtags);
                 $geo = '';
                 $geoElement = $tweet->filter('span.Tweet-geo')->first();
                 if ($geoElement->count() > 0) {
                     $geo = $geoElement->attr('title');
                 }
                 $resultTweet = new Tweet();
                 $resultTweet->setId($id);
                 $resultTweet->setPermalink("https://twitter.com" . $permalink);
                 $resultTweet->setUsername($username);
                 $resultTweet->setText($text);
                 $resultTweet->setDate($date);
                 $resultTweet->setRetweets($retweets);
                 $resultTweet->setFavorites($favorites);
                 $resultTweet->setMentions($mentions);
                 $resultTweet->setHashtags($hashtags);
                 $resultTweet->setGeo($geo);
                 $results[] = $resultTweet;
             });
         } while (count($results) < $criteria->getMaxTweets());
     } catch (\Exception $e) {
         $this->handleException($e);
         return $results;
     }
     return $results;
 }
开发者ID:yawmoght,项目名称:getoldtweets-php,代码行数:56,代码来源:TweetManager.php

示例7: findIndex

 /**
  * Find index for a value based
  *
  * @param mixed $value
  * @param int $compareLimit
  * @return int
  */
 protected function findIndex($value, int $compareLimit) : int
 {
     $begin = 0;
     $end = count($this->values) - 1;
     while ($begin <= $end) {
         $middle = intdiv($begin + $end, 2);
         if (($this->values[$middle] <=> $value) <= $compareLimit) {
             $begin = $middle + 1;
             continue;
         }
         $end = $middle - 1;
     }
     return $begin;
 }
开发者ID:fixin,项目名称:fixin,代码行数:21,代码来源:Index.php

示例8: convertMetersToYards

function convertMetersToYards($meters)
{
    // Convert meters to tenths of a millimeter
    $mmx10 = $meters * 10000;
    // Divide by 9144 to get yards
    $y = intdiv($mmx10, 9144);
    // Use modulo division to get the remainder
    $f = $mmx10 % 9144;
    // Divide by 3048 to get feet
    $ft = intdiv($f, 3048);
    // Get the remainder and convert to inches
    $i = $f % 3048;
    $i = number_format($i / 254, 2);
    return "{$y} yards {$ft} feet {$i} inches";
}
开发者ID:sydorenkovd,项目名称:php7_EasyWay,代码行数:15,代码来源:intdiv_convertMetersToYards.php

示例9: median

 /**
  * Calculate the median average of a list of numbers
  *
  * @param array $numbers
  *
  * @return number
  */
 public static function median(array $numbers)
 {
     if (empty($numbers)) {
         return null;
     }
     // Reset the array key indexes because we don't know what might be passed in
     $numbers = array_values($numbers);
     // For odd number of numbers, take the middle indexed number
     if (count($numbers) % 2 == 1) {
         $middle_index = intdiv(count($numbers), 2);
         return self::kthSmallest($numbers, $middle_index);
     }
     // For even number of items, take the mean of the middle two indexed numbers
     $left_middle_index = intdiv(count($numbers), 2) - 1;
     $left_median = self::kthSmallest($numbers, $left_middle_index);
     $right_middle_index = $left_middle_index + 1;
     $right_median = self::kthSmallest($numbers, $right_middle_index);
     return self::mean([$left_median, $right_median]);
 }
开发者ID:markrogoyski,项目名称:math-php,代码行数:26,代码来源:Average.php

示例10: var_dump

<?php

var_dump(intdiv(3, 2));
var_dump(intdiv(-3, 2));
var_dump(intdiv(3, -2));
var_dump(intdiv(-3, -2));
var_dump(intdiv(PHP_INT_MAX, PHP_INT_MAX));
var_dump(intdiv(-PHP_INT_MAX - 1, -PHP_INT_MAX - 1));
try {
    var_dump(intdiv(-PHP_INT_MAX - 1, -1));
} catch (Exception $e) {
    var_dump($e->getMessage());
}
try {
    var_dump(intdiv(PHP_INT_MIN, -1));
} catch (Exception $e) {
    var_dump($e->getMessage());
}
try {
    var_dump(intdiv(1, 0));
} catch (Exception $e) {
    var_dump($e->getMessage());
}
开发者ID:lsqtongxin,项目名称:hhvm,代码行数:23,代码来源:intdiv.php

示例11: normalized

 /**
  * Returns a copy of this Period with the years and months normalized.
  *
  * This normalizes the years and months units, leaving the days unit unchanged.
  * The months unit is adjusted to have an absolute value less than 12,
  * with the years unit being adjusted to compensate. For example, a period of
  * "1 year and 15 months" will be normalized to "2 years and 3 months".
  *
  * The sign of the years and months units will be the same after normalization.
  * For example, a period of "1 year and -25 months" will be normalized to
  * "-1 year and -1 month".
  *
  * @return Period
  */
 public function normalized()
 {
     $totalMonths = $this->years * LocalTime::MONTHS_PER_YEAR + $this->months;
     $splitYears = intdiv($totalMonths, 12);
     $splitMonths = $totalMonths % 12;
     if ($splitYears === $this->years || $splitMonths === $this->months) {
         return $this;
     }
     return new Period($splitYears, $splitMonths, $this->days);
 }
开发者ID:brick,项目名称:date-time,代码行数:24,代码来源:Period.php

示例12: testIntdivByZero

 /**
  * @expectedException DivisionByZeroError
  */
 public function testIntdivByZero()
 {
     intdiv(1, 0);
 }
开发者ID:remicollet,项目名称:polyfill,代码行数:7,代码来源:Php70Test.php

示例13: getNonce

 /**
  * Get (and increment) the nonce for AES-CTR
  * 
  * @param int $increment
  * @return string
  */
 protected function getNonce(int $increment = 0) : string
 {
     $nonce = '';
     $ctr = $this->counter;
     while ($ctr > 0) {
         $nonce = \chr($ctr & 0xff) . $nonce;
         $ctr >>= 8;
     }
     $this->counter += intdiv($increment + $increment % 16, 16);
     return \str_pad($nonce, 16, "", STR_PAD_LEFT);
 }
开发者ID:dbarr,项目名称:seedspring,代码行数:17,代码来源:SeedSpring.php

示例14: flush

 /**
  * Used by all styles of Eve APIs to prepare and execute their SQL 'upsert' queries.
  *
  * 'Upsert' is a commonly used term for updating any existing rows in a table and inserting all the ones that don't
  * already exist together at one time.
  *
  * The method also tracks if the prepared query can be re-used or not to take fuller advantage of them in cases
  * where all queries have the same number of database rows as is common with some of the larger APIs and a few that
  * always have a fixed number of rows.
  *
  * @param string[] $columns
  * @param string[] $columnNames
  * @param string   $tableName
  *
  * @return self Fluent interface.
  * @throws \DomainException
  * @throws \InvalidArgumentException
  * @throws \LogicException
  */
 protected function flush(array $columns, array $columnNames, string $tableName)
 {
     if (0 === count($columns)) {
         return $this;
     }
     $rowCount = intdiv(count($columns), count($columnNames));
     $mess = sprintf('Have %1$s row(s) to upsert into %2$s table', $rowCount, $tableName);
     $this->getYem()->triggerLogEvent('Yapeal.Log.log', Logger::INFO, $mess);
     $isNotPrepared = $this->lastColumnCount !== count($columnNames) || $this->lastRowCount !== $rowCount || null === $this->pdoStatement;
     if ($isNotPrepared) {
         $sql = $this->getCsq()->getUpsert($tableName, $columnNames, $rowCount);
         $mess = preg_replace('%(,\\([?,]*\\))+%', ',...', $sql);
         $lastError = preg_last_error();
         if (PREG_NO_ERROR !== $lastError) {
             $constants = array_flip(get_defined_constants(true)['pcre']);
             $lastError = $constants[$lastError];
             $mess = 'Received preg error ' . $lastError;
             throw new \DomainException($mess);
         }
         $this->getYem()->triggerLogEvent('Yapeal.Log.log', Logger::INFO, $mess);
         $this->pdoStatement = $this->getPdo()->prepare($sql);
         $this->lastColumnCount = count($columnNames);
         $this->lastRowCount = $rowCount;
     }
     $mess = '';
     foreach ($columns as $column) {
         $mess .= $column . ',';
         if (256 <= strlen($mess)) {
             break;
         }
     }
     $mess = substr($mess, 0, 256) . '...';
     $this->getYem()->triggerLogEvent('Yapeal.Log.log', Logger::DEBUG, $mess);
     $this->pdoStatement->execute($columns);
     return $this;
 }
开发者ID:yapeal,项目名称:yapeal-ng,代码行数:55,代码来源:PreserverTrait.php

示例15: testSmallestNumber

 /**
  * @expectedException ArithmeticError
  */
 public function testSmallestNumber()
 {
     intdiv(~PHP_INT_MAX, -1);
 }
开发者ID:AndrewCarterUK,项目名称:intdiv_compat,代码行数:7,代码来源:IntdivTest.php


注:本文中的intdiv函数示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。