rgb192
asked on
array
Fill array from 1 to 512. Echo only values that are powers of 2
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
<?php
$power = 2;
// fill an array with numbers
for ($i=1;$i < 513; $i++) {
$joe[] = $i;
$check = log($i) / log($power);
// if $check is an integer then it is a power of 2
if ($check == intval($check)) {
echo $i ."<BR>\n";
}
}
//var_dump($joe);
?>
$power = 2;
// fill an array with numbers
for ($i=1;$i < 513; $i++) {
$joe[] = $i;
$check = log($i) / log($power);
// if $check is an integer then it is a power of 2
if ($check == intval($check)) {
echo $i ."<BR>\n";
}
}
//var_dump($joe);
?>
sounds like a school problem, but the array is extraneous unless the check must be done while filling the array.
2^x = y (2 to the power of x)
x log 2 = log y
x = (log y) / (log 2)
Since the last line is true then all integer values of x are powers of 2 for the input y = 1..512
2^x = y (2 to the power of x)
x log 2 = log y
x = (log y) / (log 2)
Since the last line is true then all integer values of x are powers of 2 for the input y = 1..512
ASKER
I get all values on code sample 1
I'm with themrrobert on this one. You didn't give us enough information.
If you really wanted it in an array, you could take robert's example and modify it.
Note that this method will leave a blank record at the end you will need to account for.
If you really wanted it in an array, you could take robert's example and modify it.
$array_variable = NULL;
for($x=0;$x<10;$x++){
$array_variable .= pow(2,$x) . ",";
}
$array = explode(",",$array_variable);
Note that this method will leave a blank record at the end you will need to account for.
ASKER
Thanks
echo "2 to the x($x) power = " . pow(2, $x)."<br />";
results:
2 to the x(0) power = 1
2 to the x(1) power = 2
2 to the x(2) power = 4
2 to the x(3) power = 8
2 to the x(4) power = 16
2 to the x(5) power = 32
2 to the x(6) power = 64
2 to the x(7) power = 128
2 to the x(8) power = 256
2 to the x(9) power = 512