-
-
Save dekajp/4676999 to your computer and use it in GitHub Desktop.
The 3n + 1 problem
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
Problem URL: http://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&problem=36 | |
Home>Online Judge > submission Specifications | |
Sample code to read input is from : http://online-judge.uva.es/problemset/data/p100.java.html | |
Runtime : 1.068 | |
*/ | |
import java.io.*; | |
import java.util.*; | |
class Main | |
{ | |
static String ReadLn (int maxLg) // utility function to read from stdin | |
{ | |
byte lin[] = new byte [maxLg]; | |
int lg = 0, car = -1; | |
String line = ""; | |
try | |
{ | |
while (lg < maxLg) | |
{ | |
car = System.in.read(); | |
if ((car < 0) || (car == '\n')) break; | |
lin [lg++] += car; | |
} | |
} | |
catch (IOException e) | |
{ | |
return (null); | |
} | |
if ((car < 0) && (lg == 0)) return (null); // eof | |
return (new String (lin, 0, lg)); | |
} | |
public static void main (String args[]) // entry point from OS | |
{ | |
Main myWork = new Main(); // create a dinamic instance | |
myWork.Begin(); // the true entry point | |
} | |
void Begin() | |
{ | |
String input; | |
StringTokenizer idata; | |
int a, b,max; | |
while ((input = Main.ReadLn (255)) != null) | |
{ | |
idata = new StringTokenizer (input); | |
a = Integer.parseInt (idata.nextToken()); | |
b = Integer.parseInt (idata.nextToken()); | |
if (a<b){ | |
max=work(a,b); | |
}else{ | |
max=work(b,a); | |
} | |
System.out.println (a + " " + b + " " +max); | |
} | |
} | |
int work( int a , int b){ | |
int max=0; | |
for ( int i=a;i<=b;i++){ | |
int temp=process(i); | |
if (temp>max) max=temp; | |
} | |
return max; | |
} | |
int process (long n){ | |
int count=1; | |
while(n!=1){ | |
count++; | |
if (n%2==1){ | |
n=n*3+1; | |
}else{ | |
n=n>>1; | |
} | |
} | |
return count; | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment