Skip to content

Instantly share code, notes, and snippets.

@gtke
Created March 28, 2014 04:10
Show Gist options
  • Save gtke/9825202 to your computer and use it in GitHub Desktop.
Save gtke/9825202 to your computer and use it in GitHub Desktop.
package DynamicProgramming;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Scanner;
public class ThreeNPlusOne {
public static void main(String [] args) throws NumberFormatException, IOException{
ArrayList<Integer> arr = new ArrayList<Integer>();
final BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
String line;
while((line = in.readLine()) != null){
String REGEX_WHITESPACE = "\\s+";
String cleanLine = line.trim().replaceAll(REGEX_WHITESPACE, " ");
String[] tokens = cleanLine.split(REGEX_WHITESPACE);
if (tokens.length == 2) {
int a = Integer.parseInt(tokens[0]);
int b = Integer.parseInt(tokens[1]);
for(int j=a; j<=b; j++){
arr.add(foo(j));
}
Collections.sort(arr);
System.out.println(a + " " + b + " " + arr.get(arr.size()-1));
arr = new ArrayList<Integer>();
}
}
}
public static int foo(int n){
int ans = 1;
while(n>1){
if((n & 1) == 1) {
n = 3*n + 1;
}else{
n = n/2;
}
ans++;
}
return ans;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment