//ProjectEuler/Java/Problem14.java //Matthew Ellison // Created: 03-04-19 //Modified: 03-28-19 /* The following iterative sequence is defined for the set of positive integers: n → n/2 (n is even) n → 3n + 1 (n is odd) Which starting number, under one million, produces the longest chain? */ //Unless otherwise listed all non-standard includes are my own creation and available from https://bibucket.org/Mattrixwv/JavaClasses /* Copyright (C) 2019 Matthew Ellison This program is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program. If not, see . */ import mattrixwv.Stopwatch; import mattrixwv.Algorithms; public class Problem14{ private static final Long MAX_NUM = 1000000L; //This is the top number that you will be checking against the series public static void main(String[] argv){ Stopwatch timer = new Stopwatch(); //This allows the run time of the algorithm to be testd Long maxLength = 0L; //This is the length of the longest chain Long maxNum = 0L; //This is teh starting number of the longest chain //Start the timer timer.start(); //Loop through all numbers less than MAX_NUM and check them against the series for(Long currentNum = 1L;currentNum < MAX_NUM;++currentNum){ Long currentLength = checkSeries(currentNum); //If the current number has a longer series than the max then the current becomes the max if(currentLength > maxLength){ maxLength = currentLength; maxNum = currentNum; } } //Stop the timer timer.stop(); //Print the results System.out.printf("The number %d produced a chain of %d steps\n", maxNum, maxLength); System.out.println("It took " + timer.getStr() + " to run this algorithm"); } //This function follows the rules of the sequence and returns its length private static Long checkSeries(Long num){ Long length = 1L; //Start at 1 becuase you need to count the starting number //Follow the series, adding 1 for each step you take while(num > 1){ if((num % 2) == 0){ num /= 2; } else{ num = (3 * num) + 1; } ++length; } //Return the length of the series return length; } } /* Results: The number 837799 produced a chain of 525 steps It took 1.006 seconds to run this algorithm */