Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR JAVA

3x+1 in java

import java.util.*;

class solution {


public static int[] clength = new int[1000000];

public static long nextnum(long n)
{

    if(n%2==0)
    {
        return n/2;
    }
    else
        return 3*n+1;
}

public static long cyclelength(long n)
{

    if(n==1)
    {
        return 1;

    }
    if (n < 1000000 && clength[(int)n] != 0)
    {
        return clength[(int)n];

    }
    long length= (1+ cyclelength(nextnum(n)));
    if (n < 1000000)
        clength[(int)n] = (int) length;

    return length;
}

public static void main(String[] args) throws Exception {
    // TODO Auto-generated method stub
    Scanner in = new Scanner(System.in);

    while(in.hasNext())
    {
        int a=in.nextInt();
        int b=in.nextInt();
        int min=Math.min(a, b);
        int max=Math.max(a, b);
        int count=0;

        for(int n=min;n<=max;n++)
        {
            count=(int) Math.max(count,cyclelength(n));

        }
        System.out.println(a + " " + b +" " +count );
    }
}

}
Source by stackoverflow.com #
 
PREVIOUS NEXT
Tagged: #java
ADD COMMENT
Topic
Name
9+3 =