Exercise : Show Twos (by Alex Miller)

Write a PHP function show_twos that takes an integer parameter and outputs its factors of 2 with HTML. For example:

show_twos(68);
show_twos(18);
show_twos(68);
show_twos(120);

should produce the following output:

<strong>68</strong> = 2 * 2 * 17<br/>
<strong>18</strong> = 2 * 9<br/>
<strong>68</strong> = 2 * 2 * 17<br/>
<strong>120</strong> = 2 * 2 * 2 * 15<br/>

If you have time, wrap the code in a page that accepts a query parameter num and passes that parameter to the function.

Exercise Solution

<?php
function show_twos($n) { ?>
   <strong><?= $n ?></strong> =
   <?php
   while ($n % 2 == 0) {
      print "2 *";
      $n = $n / 2;
   }
   ?>
   <?= $n ?><br />
   <?php
}

show_twos($_GET["num"]);
?>