Advertisement
Guest User

Collatz

a guest
Jun 29th, 2014
242
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.38 KB | None | 0 0
  1. public class CollatzProblem {
  2.  
  3.     public static void main(String[] args) {
  4.         // This is the number the program will go up to, so to find maximum from 1 to 100, we make k = 100
  5.         int k = 1000000;
  6.         // An array to keep track of the values we get
  7.         int[] length = new int[k];
  8.        
  9.         // Loop through all possible starting values, from 1 to 'k'
  10.         for(int start = 1; start < k; ++start){
  11.             int current = start;
  12.             int count = 0;
  13.            
  14.             // This is where iteration happens, we keep iterating until we get a '1'
  15.             // While doing so it counts each iteration
  16.             while(current != 1){
  17.                 current = iterate(current); // See next method to see how it iterates
  18.                 ++count;
  19.             }
  20.            
  21.             length[start] = count;
  22.            
  23.         }
  24.         // This will find the actual maximum value in the array
  25.         int max = length[0];
  26.        
  27.         for(int i=0; i< k; ++i){
  28.             if(max < length[i]){
  29.                 max = length[i];
  30.             }
  31.         }
  32.         // This will find the value that belongs to this 'max', this is the value we want
  33.         int maxIndex = 0;
  34.        
  35.         for(int i=0; i<k; ++i){
  36.             if(max == length[i]){
  37.                 maxIndex = i;
  38.             }
  39.         }
  40.        
  41.         System.out.println("Index: " + maxIndex + " Amount: " + max);
  42.        
  43.     }
  44.    
  45.     public static int iterate(int n){
  46.         // Do as the function says, if n is even, halve it, if n is odd, 3*n+1 is output
  47.         int out = 0;
  48.        
  49.         if(n%2 == 0){
  50.             out = n/2;
  51.         }
  52.         if(n%2 != 0){
  53.             out = 3*n+1;
  54.         }
  55.         return out;
  56.     }
  57.  
  58. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement