Wednesday 4 June 2014

Collatz Conjecture - Implementation in Java

Let's begin with a short intro to Collatz Conjecture*. It's also known in the names (3n+1) conjecture, Hasse's Algorithm, Syracuse problem, and a ton of others I really have a hard time remembering. The problem can be represented as a mathematical function as given below, which is iterated until the value of variable is reduced to 1.


The proposal of Collatz conjecture, is that, no matter what number you start with, you will eventually, at some point, reach 1. We all know that computers are especially good at repeating stuff! For this reason, many mathematicians, and computer scientists rely upon algorithms and computers to test these kind of problems. There is a lot of underlying math to this problem, some of which you can see at Wikipedia, and Wolfram Alpha. I'm not going into the math. Here is the code:


/* Implementation of Collatz Conjecture/ Hasse's Algorithm/ Syracuse Problem in Java using Recursion */
import java.util.Scanner;

public class CollatzConjecture {
    public static void Collatz(int x) {
        System.out.print(x + ", ");
        if (x == 1) {
           return; 
           // If x is 1, then the function is terminated
        } 
        else if (x % 2 == 0) {
           Collatz(x / 2);       
           // If x is even, then function is called with the argument x/2
        } 
        else if (x % 2 != 0) {
           Collatz((3 * x) + 1); 
           // If x is odd, then function is called with the argument 3x+1
        }
    }

    public static void main(String[] args) {
       System.out.print("Collatz Conjecture");
       System.out.print("\nEnter the starting number: ");
       Scanner in = new Scanner(System.in);
       int n = in.nextInt();
       Collatz(n);
       in.close();
   }
}

I have used recursion to carry out the iteration, you may also use any loop of your choice.
Here is a sample output. As you can see, even a number as small as 27 takes 111 steps to reach unity, and it touches a number as large as 9232 on its way!

27 reaches unity, taking 111 steps, touching the maximum 9232 on its way!


Don't jump into conclusions though. Specific numbers, as large as 1024, takes only 10 steps to reach 1. This is because 1024 is the tenth power of 2.

1024 reaches unity faster, because it is a power of 2


From these examples, it is safe to say that the number of steps taken is purely depended upon the nature of the number. Some numbers tend to reach 1 faster, and some takes a larger amount of time. This is the magic of Mathematics!

*Conjecture - An unproved proposition
Happy Coding!
:)

No comments:

Post a Comment

You might also like