Advertisement
redzonex

euler14

Aug 10th, 2016
86
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.11 KB | None | 0 0
  1. /**
  2. * Created by RedzoneX on 8/10/16.
  3. */
  4. public class LongestCollatz {
  5. public static int findCollatz() {
  6. int maxTerms = 0;
  7. int maxNum = 0;
  8. int[] array = new int[1000000];
  9. for (int i = 1; i < 1000000; i++) {
  10. long num = i;
  11. int terms = 1;
  12. while (num != 1) {
  13. if (num % 2 != 0)
  14. num = 3 * num + 1;
  15. else
  16. num /= 2;
  17. terms++;
  18. if (num < i) {
  19. terms += array[(int)num] - 1;
  20. break;
  21. }
  22. }
  23. array[i] = terms;
  24. if (terms > maxTerms) {
  25. maxTerms = terms;
  26. maxNum = i;
  27. }
  28. }
  29. return maxNum;
  30. }
  31. public static void main(String[] args) {
  32. long start = System.currentTimeMillis();
  33. int number = findCollatz();
  34. long end = System.currentTimeMillis();
  35. System.out.println(number);
  36. System.out.println("That took " + (end - start) + " milliseconds.");
  37. }
  38. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement