Search code examples
phpalgorithmgmp

Convert GMP integer to a sum of power of two (2n)


I'm using GMP library of php to solve a problem of formulary.

public function gmp_sum($aRessource)
{
    // Avec le while
    $i = 0;
    $nb_ressource = count($aRessource);
    while ($i < $nb_ressource)
    {   
        if ($i == 0)
        {
            $tmp = gmp_init($aRessource[$i]);
        }
        else
        {
            $tmp = gmp_add(gmp_init($aRessource[$i]),$tmp);
        }
        $i++;
    }
    return $tmp;
}

The variable $aRessource is equal to : array(1,2,4,8);

so my function gmp_sum is returning 15.

I want to create an algorithm who does the reverse operation, the function take the integer 15 and return me an array who contains 1 2 4 8. But I do not know where to start.

Thanks for the help

Solution :

Decompose integer to power of 2 in php

    public function gmp_reverse($gmp_sum)
{
    $res = array();
    $i = 1;
    while ($i < 64) // 64 bytes
    {   
        $tmp = $gmp_sum & $i; // check if bytes equal to 1
        if ($tmp != 0)
        {
            array_push($res,$i);
        }
        $i = $i * 2;
    }
    return $res;
}

Solution

  • Assuming you want an array which adds up to the sum, you want a reverse of that. This function assumes, you have a perfect input, so for example, 17 will not work. Try it out.

    function reversegen($gmpsum)
    {
        $stack = array();
        $limit = $gmpsum;
        $cur = 1;
        for($sum = 0; $sum < $limit; )
        {
            echo $cur. "<br>";
            array_push($stack,$cur);
            $sum = $sum + $cur;
            $cur = 2 * $cur;
        }
        return($stack);
    }
    
    
    $stack = reversegen(15);
    print_r($stack);
    

    15 above is for representative purpose. You can use, 31, 63, 127 etc and it will still work fine.