开发者

representation of any number in power of '2' using PHP

I tried to play with php,however I got stuck at one place, where I tested value of $n=1024, then it takes more than 60sec,so timeout error of php arises,I don't know how to overcome this problem,if my only requirement is to present any input number in the 20 + ---+ 2n Form.
trying below code with n=121,I got this,but I wish to represent 57 also in 2n Form,So I tried recursion,which didn't worked.

see how a given no. be represented in powers of '2':

20 + 21 + 22 + 2 + 24+ 25 + 26+ 57

CODE:

<?php

echo("see how a given no. be represented in powers of '2' :<br/>\n");

$n=121;
$two_pow=array(
    pow(2,0),pow(2,1),pow(2,2),pow(2,3),pow(2,4),pow(2,5),
    pow(2,6),pow(2,7),pow(2,8),pow(2,9),pow(2,10)
);
//print_r($two_pow);


$i=0;

while($n>=$two_pow[$i])
    $i++;

/* displaying  2^3*/
if($i>0)
    $ij=$i-1;

/* diplaying difference of give N and 2^i*/
$diff=$n-$two_pow[$ij];

if($n>0)
{
    for($i=0;$开发者_StackOverflowi<=$ij;$i++)
    {
        echo("2<sup> $i </sup>"."+ \n");

        if($i==$ij && $diff>0)
        {
            echo("\n". $diff);
        }
    }
}
else 
    echo("<br/>not possible for values less then zero");

?>


No need for recursion or anything like that, just convert to binary and loop through the characters:

$bits = array_reverse(str_split(decbin($n)));
$output = array();
foreach($bits as $key => $bit) {
    if($bit == 1) {
        $output[] = '2<sup>'.($key).'</sup>';
    }
}
echo implode(' + ', $output);

Working example:

http://codepad.org/plzvw2RL


Cant you use - base_convert() to convert the string to binary, then format your output based on the position of bits?


It is a joke right? Oh it isn't? Well ok take look at decbin function. Isn't it easier?


You can overcome the timeout restriction by disabling the timeout:

set_time_limit(0);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜