Guest User

Untitled

a guest
Jan 14th, 2018
72
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.07 KB | None | 0 0
  1. package threenplusone;
  2.  
  3. public class HailstoneLengthQuick {
  4.     private int max;
  5.  
  6.     public static void main(String[] args) {
  7.         HailstoneLengthQuick hlq = new HailstoneLengthQuick();
  8.         // TODO: validate input so we can assume input is in the form 'a, b' where b>=a and b,a>0
  9.  
  10.         // parse the input into lower and upper bounds for the range on which we want to compute.
  11.         int lower = 1;
  12.         int upper = 2;
  13.         try {
  14.             lower = Integer.parseInt(args[0]);
  15.             upper = Integer.parseInt(args[1]);
  16.         }  
  17.         catch (java.lang.ArrayIndexOutOfBoundsException ex) { }
  18.        
  19.         // the outer loop
  20.         int workingMax = 0;
  21.         for (int n = lower; n <= upper; n++) {
  22.             workingMax = hlq.collatzCount(n);
  23.             if (workingMax > hlq.max) {
  24.                 hlq.max = workingMax;
  25.             }
  26.         }
  27.        
  28.         System.out.println(lower + " " + upper + " " + hlq.max);
  29.     }
  30.    
  31.     public int collatzCount(int n) {
  32.         int count = 1;
  33.         // the inner loop
  34.         while (n>1) {
  35.             count++;
  36.             if (n%2 == 0) { //n even
  37.                 n = n>>1;
  38.             }
  39.             else {
  40.                 n = (3*n) + 1;
  41.             }
  42.         }
  43.         return count;
  44.     }
  45.    
  46.     int getMax() {
  47.         return max;
  48.     }
  49. }
Add Comment
Please, Sign In to add comment