First, solve the problem. Then, write the code. ” - John Johnson

It's not at all important to get it right the first time. It's vitally important to get it right the last time. ” - Andrew Hunt and David Thomas

Tuesday, July 15, 2014

The 3n + 1 problem

Name of programmer: Jisan
Programming language: Java
Difficulty: Easy
Status: Accepted
Problem number: UVA-100
http://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&problem=36

Help:http://docs.oracle.com/javase/7/docs/api/java/lang/Math.html

Code:

import java.util.*;

public class Uva_100 {

    public static void main(String[] args) {
        Scanner s = new Scanner(System.in);
        int i, j, high, count, min, max, temp;
        while(s.hasNext()) {
            i = s.nextInt();
            j = s.nextInt();
            min = Math.min(i, j);
            max = Math.max(i, j);
            high = 0;
            for(int n = min; n <= max; n++){
                count = 1;
                 temp=n;
                while(true) {
                    if(temp == 1)
                        break;
                    if(temp % 2 == 0)
                        temp = temp / 2;
                    else
                        temp = 3 * temp + 1;
                    count++;
                }
                if(high < count)
                    high = count;
            }
            System.out.println(i + " " + j + " " + high);
        }
    }
}

No comments:

Post a Comment