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
- double k = 1000000;
- // An array to keep track of the values we get
- double[] length = new double[(int)k];
- // Loop through all possible starting values, from 1 to 'k'
- for(double start = 1; start < k; ++start){
- double current = start;
- double 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[(int)start] = count;
- }
- // This will find the actual maximum value in the array
- double max = length[0];
- for(double i=0; i< k; ++i){
- if(max < length[(int)i]){
- max = length[(int)i];
- }
- }
- // This will find the value that belongs to this 'max', this is the value we want
- double maxIndex = 0;
- for(double i=0; i<k; ++i){
- if(max == length[(int)i]){
- maxIndex = i;
- }
- }
- System.out.println("Index: " + maxIndex + " Amount: " + max);
- }
- public static double iterate(double n){
- // Do as the function says, if n is even, halve it, if n is odd, 3*n+1 is output
- double 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