Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public class ProjectEuler14
- {
- public static void main(String[] args)
- {
- double timeStart = System.currentTimeMillis();
- Collatz c = new Collatz();
- int highestNumOfTerms = 0;
- int currentNumOfTerms = 0;
- int n = 0; //Value which produces most number of Collatz terms
- for (double i = 1.; i <= 1000000.; i++)
- {
- currentNumOfTerms = c.startCollatz(i);
- if (currentNumOfTerms > highestNumOfTerms)
- {
- highestNumOfTerms = currentNumOfTerms;
- n = (int)(i);
- System.out.println("New term: " + n);
- }
- }
- double timeStop = System.currentTimeMillis();
- System.out.println("Highest term: " + n + " with " + highestNumOfTerms + " number of terms");
- System.out.println("Completed in " + ((timeStop - timeStart)/1000) + " s");
- }
- }
- public class Collatz
- {
- private static int numOfTerms = 0;
- private boolean isFirstRun = false;
- public int startCollatz(double n)
- {
- isFirstRun = true;
- runCollatz(n);
- return numOfTerms;
- }
- private void runCollatz(double n)
- {
- if (isFirstRun)
- {
- numOfTerms = 0;
- isFirstRun = false;
- }
- if (n == 1)
- {
- //Do Nothing
- //Causes return to startCollatz()
- }
- else if (n % 2 == 0)
- {
- //Divides n by 2 following Collatz rule, running recursion
- numOfTerms = numOfTerms + 1;
- runCollatz(n / 2);
- }
- else if (n % 2 == 1)
- {
- //Multiples n by 3 and adds one, following Collatz rule, running recursion
- numOfTerms = numOfTerms + 1;
- runCollatz((3 * n) + 1);
- }
- //return numOfTerms;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment