Gets the length of a collatz sequence chain - Java java.lang

Java examples for java.lang:Math Algorithm

Description

Gets the length of a collatz sequence chain

Demo Code


import java.io.*;
import java.math.BigInteger;
import java.util.*;

public class Main{
    /**// w w w.  j  a  va 2 s .  c  o m
     * Gets the length of a collatz sequence chain
     *
     * @param start Start number
     * @return Length of the chain
     */
    public static long collatzChainLength(long start) {
        long chainLength = 1;
        long i = start;
        while (i != 1) {
            ++chainLength;
            if (HelperFunctions.isEven(i)) {
                i = i / 2;
            } else {
                i = (3 * i) + 1;
            }
        }
        return chainLength;
    }
    /**
     * Gets if a number is even
     *
     * @param num Number to test
     * @return If a number is even
     */
    public static boolean isEven(long num) {
        return (num % 2 == 0);
    }
}

Related Tutorials