Guest User

Untitled

a guest
Jul 14th, 2014
251
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.88 KB | None | 0 0
  1. public class ProjectEuler14
  2. {
  3.     public static void main(String[] args)
  4.     {
  5.         double timeStart = System.currentTimeMillis();
  6.  
  7.         Collatz c = new Collatz();
  8.         int highestNumOfTerms = 0;
  9.         int currentNumOfTerms = 0;
  10.         int n = 0; //Value which produces most number of Collatz terms
  11.  
  12.  
  13.         for (double i = 1.; i <= 1000000.; i++)
  14.         {
  15.             currentNumOfTerms = c.startCollatz(i);
  16.  
  17.  
  18.             if (currentNumOfTerms > highestNumOfTerms)
  19.             {
  20.                 highestNumOfTerms = currentNumOfTerms;
  21.                 n = (int)(i);
  22.                 System.out.println("New term: " + n);
  23.             }
  24.         }
  25.  
  26.         double timeStop = System.currentTimeMillis();
  27.  
  28.         System.out.println("Highest term: " + n + " with " + highestNumOfTerms + " number of terms");
  29.         System.out.println("Completed in " + ((timeStop - timeStart)/1000) + " s");
  30.     }
  31. }
  32.  
  33.  
  34.  
  35. public class Collatz
  36. {
  37.     private static int numOfTerms = 0;
  38.     private boolean isFirstRun = false;
  39.  
  40.     public int startCollatz(double n)
  41.     {
  42.         isFirstRun = true;
  43.         runCollatz(n);
  44.         return numOfTerms;
  45.     }
  46.  
  47.     private void runCollatz(double n)
  48.     {
  49.         if (isFirstRun)
  50.         {
  51.             numOfTerms = 0;
  52.             isFirstRun = false;
  53.         }
  54.  
  55.         if (n == 1)
  56.         {
  57.             //Do Nothing
  58.             //Causes return to startCollatz()
  59.         }
  60.  
  61.         else if (n % 2 == 0)
  62.         {
  63.             //Divides n by 2 following Collatz rule, running recursion
  64.             numOfTerms = numOfTerms + 1;
  65.             runCollatz(n / 2);
  66.         }
  67.  
  68.         else if (n % 2 == 1)
  69.         {
  70.             //Multiples n by 3 and adds one, following Collatz rule, running recursion
  71.             numOfTerms = numOfTerms + 1;
  72.             runCollatz((3 * n) + 1);
  73.         }
  74.  
  75.         //return numOfTerms;
  76.     }
  77. }
Advertisement
Add Comment
Please, Sign In to add comment