Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package threenplusone;
- public class HailstoneLengthQuick {
- private int max;
- public static void main(String[] args) {
- HailstoneLengthQuick hlq = new HailstoneLengthQuick();
- // TODO: validate input so we can assume input is in the form 'a, b' where b>=a and b,a>0
- // parse the input into lower and upper bounds for the range on which we want to compute.
- int lower = 1;
- int upper = 2;
- try {
- lower = Integer.parseInt(args[0]);
- upper = Integer.parseInt(args[1]);
- }
- catch (java.lang.ArrayIndexOutOfBoundsException ex) { }
- // the outer loop
- int workingMax = 0;
- for (int n = lower; n <= upper; n++) {
- workingMax = hlq.collatzCount(n);
- if (workingMax > hlq.max) {
- hlq.max = workingMax;
- }
- }
- System.out.println(lower + " " + upper + " " + hlq.max);
- }
- public int collatzCount(int n) {
- int count = 1;
- // the inner loop
- while (n>1) {
- count++;
- if (n%2 == 0) { //n even
- n = n>>1;
- }
- else {
- n = (3*n) + 1;
- }
- }
- return count;
- }
- int getMax() {
- return max;
- }
- }
Add Comment
Please, Sign In to add comment