# ThreeNPlus1 form solution

```<?php
/*
* Created on Feb 13, 2008
*
* In class example.
* Write a PHP script that computes the 3N+1 problem. For N > 0,
*  generate a sequence of numbers using the following simple rules:
*  if N is even, divide it by 2; if N is odd, multiply it by 3 and add 1.
*  The sequence always converges to 1, although the length of the sequence
*  varies depending on the choice of N.
*
*  This version uses a simple HTML <FORM> element to get user's input.
*/
?>
<HTML>
<TITLE>3N + 1 Problem</TITLE>
<BODY>
<H4>The 3N + 1 Problem</h4>
<?php
// \$_SERVER['PHP_SELF'] returns the name of this file, which
//  serve as the handler for this form.
\$self = htmlentities(\$_SERVER['PHP_SELF']);

// \$_GET['N'] gets the value from the form element named 'N'.
// The htmlentities() function cleans up the input string as a security measure.
\$n = htmlentities(\$_GET["N"]); //
if (\$n == '') {      // If \$n has not been set, display the form.
echo ('
<form action="'.\$self.'" method="GET">
<label>N: <input type="text" name="N" /></label>
<input type="submit" value="go!" />
</form>');
}
else {               // Otherwise, display the 3N+1 sequence
echo "N= \$n<BR>";
while (\$n > 1) {        // While n is greater than 1
echo "\$n<BR>";      // Print it then either
if (\$n % 2 == 0) {
\$n = \$n / 2;    //  Divide it by 2
}
else {
\$n = 3 * \$n + 1;  // Or multiply 3N+1
}
}
}

?>
</BODY>
</HTML>

```