## “Presto” math trick in Java

June 23rd, 2010

According to Futility Closet, if you start with a 3 digit and place it next to the same number to form a 6 digit number, you can divide the 6 digit number by 7, 11, and then 13 and you will end up with the original 3 digit number and no remainders.  For example, by taking the number 412 and making it 412412 and then doing the divisions, you will end up with 412.  I wrote a small program in Java to test it.

### The Code

1. public class Main
2. {
3.     public static void main(String[] args)
4.     {
5.         for(int i = 100; i <= 999; i++)
6.         {
7.             //get the number, and "double" it
8.             int number = Integer.parseInt(Integer.toString(i) + Integer.toString(i));
9.
10.             //successively divided by 7, 11, then 13
11.             System.out.print((i) + "t");
12.             System.out.print((number) + "t");
13.             System.out.print((number /= 7) + "t");
14.             System.out.print((number /= 11) + "t");
15.             System.out.print(number /= 13);
16.
17.             //is the result what we expect? (input == output)
18.             if(i == number)
19.             {
20.                 System.out.print("tCorrectn");
21.             }
22.             else
23.             {
24.                 System.out.print("tIncorrect");
25.                 break;
26.             }
27.         }
28.     }
29. }

In this snippet, we loop through all 3 digit numbers (100 to 999) and output the results of each operation in a tab separated column. If the result (output) is the same as the input, we print correct and continue with the loop. Otherwise, we print incorrect and break. Give it a try!

## Recursive Collatz conjecture in PHP

May 18th, 2010

I stumbled across a blog post by Brie Gordon about the Collatz conjecture, so naturally I had to Wikipedia it. The simple story is that for any given integer, if it is even you divide it by 2 and if it is odd you multiply it by 3 and add 1. You continue this pattern with the returned numbers, and eventually the number will reach 1.  I’ve heard of it before, but not since one of my earlier computer science classes, so to commemorate the re-discovery I wrote a recursive PHP function to display the progression.  Here is the function:

1. function collatz(\$num)
2. {
3.     if(\$num == 1)
4.     {
5.         echo "<p style='color: red'>" . \$num . "</p>n";
6.         return;
7.     }
8.
9.     if(\$num % 2 == 0) //even
10.     {
11.         echo "<p style='color: green'>" . \$num . "</p>n";
12.         return collatz(\$num / 2);
13.     }
14.     else
15.     {
16.         echo "<p style='color: red'>" . \$num . "</p>n";
17.         return collatz(3 * \$num + 1);
18.     }
19. }

View Demo