Search code examples
phpgmp

Operation on Large Numbers In php


I need to solve a problem, this is what I have tried.

$sum = 0;
for($i=1; $i<=1000; $i++){     
  $sum += gmp_strval(gmp_pow($i, $i) );
}
echo $sum;

result produce as INF, is this possible to get result other than Infinity


Solution

  • Your variable $sum need to be a gmp number, or else it will be INF when you overflow php max Integer size

    <?php
    
    $sum = 0;
    for($i=1; $i<=1000; $i++){     
      $sum = gmp_add($sum, gmp_pow($i, $i));
    }
    echo gmp_strval($sum);