Friday, 10 February 2012

Root :: Problem Set Volumes :: Volume 1 :: 100 - The 3n+1 Problem



Solution :



import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Scanner;

/**
 *
 * @author XCoder
 */
class Main {

    static class Bean {

        public static long x;
        public static long y;
        public static long max;

        public String toString() {
            return x + " " + y + " " + max;
        }

        Bean(long x, long y) {
            this.x = x;
            this.y = y;
        }
    }

    public static void main(String[] args) throws FileNotFoundException, IOException {
        new Main().begin();
    }

    private void begin() {
        String str = null;
        Scanner in = new Scanner(System.in);
        while (in.hasNext()) {
            Bean tempBean = new Bean(in.nextLong(), in.nextLong());

            int max = 0;
            if (tempBean.x < tempBean.y) {
                for (long i = tempBean.x; i <= tempBean.y; i++) {
                    int temp = (int) print(i);
                    if (temp > max) {
                        max = temp;
                        tempBean.max = max;
                    }
                }
            } else {
                for (long i = tempBean.y; i <= tempBean.x; i++) {
                    int temp = (int) print(i);
                    if (temp > max) {
                        max = temp;
                        tempBean.max = max;
                    }
                }
            }
            System.out.println(tempBean);
        }
    }
    static long array[] = new long[1000000];

    public static long print(long n) {
        long count = 0;

        while (n != 1) {

            if (n > 0 && n < array.length && array[(int) n] != 0) {
                count = array[(int) n];
                break;
            }

            if (n % 2 == 0) {
                n = n / 2;
            } else {
                n = 3 * n + 1;
            }
            count++;
        }
        array[(int) n] = count;
        return count + 1;
    }
}

No comments:

Post a Comment