Looping and branching examples
This page contains some PHP examples that use loops and if/else code.
Contents |
The 3N+1 Problem
For N>0, repeatedly applying the following rules will lead to a series of integers that eventually converges at 1: If N is even, divide it by 2; if N is odd, multiply it by 3 and add 1. Write a PHP script to illustrate this problem.
Algorithm
1. Assign N a value > 1. 2. Loop while N > 1: 3. Print N. 4. If N is even 5. N = N / 2 6. Else 7. N = 3 * N + 1 8. Done.
PHP Code
<?php $n = 6; // rand(2,100); while ($n > 1) { echo "$n<BR>"; if ($n % 2 == 0) { $n = $n / 2; } else { $n = 3 * $n + 1; } } ?>
Click here for a ThreeNPlus1 solution.
The 3N+1 Form
This problem would be more interesting if the user could input the value of N rather than having it set in the program.
HTML Form
<FORM ACTION=".$self." METHOD="GET"> <LABEL>N: <INPUT TYPE="text" NAME="N" /> </LABEL> <INPUT TYPE="submit" NAME="Go!" /> </FORM>
Click here for an example that creates a ThreeNPlus1 form solution.