Mission:
Create a function that takes any whole number n greater than 0. If n is even, halve it, else multiply it by three then add one. Continue the process until it becomes 1.
Example:
collatz(7);
output:
7
22
11
34
17
52
26
13
40
20
10
5
16
8
4
2
1
Solution:
/***** * * string collatz(int $input) * * Return a string of the calculating process. * *****/ function collatz($input) { $result = $input; if($result != 1) { echo $result . "\n"; if($result % 2 == 0) { $result /= 2; } else if($result % 2 == 1) { $result = $result * 3 + 1; } ($result == 1) ? print($result . "\n") : collatz($result); } else { echo "It's already done!"; } }
Demo:
http://code.imspiration.net/collatzConjecture
Download:
currently not available