Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public class CollatzProblem {
- public static void main(String[] args) {
- // This is the number the program will go up to, so to find maximum from 1 to 100, we make k = 100
- int k = 1000000;
- // An array to keep track of the values we get
- int[] length = new int[k];
- // Loop through all possible starting values, from 1 to 'k'
- for(int start = 1; start < k; ++start){
- int current = start;
- int count = 0;
- // This is where iteration happens, we keep iterating until we get a '1'
- // While doing so it counts each iteration
- while(current != 1){
- current = iterate(current); // See next method to see how it iterates
- ++count;
- }
- length[start] = count;
- }
- // This will find the actual maximum value in the array
- int max = length[0];
- for(int i=0; i< k; ++i){
- if(max < length[i]){
- max = length[i];
- }
- }
- // This will find the value that belongs to this 'max', this is the value we want
- int maxIndex = 0;
- for(int i=0; i<k; ++i){
- if(max == length[i]){
- maxIndex = i;
- }
- }
- System.out.println("Index: " + maxIndex + " Amount: " + max);
- }
- public static int iterate(int n){
- // Do as the function says, if n is even, halve it, if n is odd, 3*n+1 is output
- int out = 0;
- if(n%2 == 0){
- out = n/2;
- }
- if(n%2 != 0){
- out = 3*n+1;
- }
- return out;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement