搜尋此網誌

2011年7月29日 星期五

ACM-3n+1 Problem

It is a Java solution.
You should focus on the green part and fix input part for your use.


package acm;

import java.io.*;
import java.util.*;

public class ThreeNPlusOne {
public static void main(String[] args) throws IOException {
ArrayList<String> userInput = new ArrayList<String>();
int intCases = 0;
System.out.println("How many test cases to run?");
BufferedReader bs = new BufferedReader(new InputStreamReader(System.in));
String cases = bs.readLine();
intCases = Integer.parseInt(cases);
while (intCases != userInput.size()) {
System.out
.println("Please enter 2 numbers m and n,separate them by dot.");
userInput.add(bs.readLine());
}
Iterator it = userInput.iterator();
while (it.hasNext()) {
String numbers = (String) (it.next());
int[] ns = getInts(numbers);
int first = ns[0];
int second = ns[1];
System.out.println(first + " " + second + " "+ threeN(first, second));
}

}

public static int threeN(int a, int b) {
int max= 0;
for (int i = a; i <= b; ) {
int tmp=i;
int count = 0;
while (true) {
count++;
if (i == 1) {
break;
} else {
if (i % 2 != 0) {
i = 3 * i + 1;
} else {
i /= 2;
}
}
}
if (count > max) {
max = count;
}
i=++tmp;
}
return max;
}

public static int[] getInts(String str) {
int totalNumbers = str.split(",").length;
int[] ints = new int[totalNumbers];
for (int i = 0; i < totalNumbers; i++) {
ints[i] = Integer.parseInt(str.split(",")[i].trim());
}
return ints;
}

}

沒有留言:

張貼留言