LongestCollatzSequence.java 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. /* The following iterative sequence is defined for the set of
  2. positive integers:
  3. n → n/2 (n is even)
  4. n → 3n + 1 (n is odd)
  5. Using the rule above and starting with 13, we generate the following sequence:
  6. 13 → 40 → 20 → 10 → 5 → 16 → 8 → 4 → 2 → 1
  7. It can be seen that this sequence (starting at 13 and finishing at 1)
  8. contains 10 terms. Although it has not been proved yet (Collatz Problem), it is
  9. thought that all starting numbers finish at 1.
  10. Which starting number, under one million, produces the longest chain?
  11. NOTE: Once the chain starts the terms are allowed to go above one million.
  12. The Collatz conjecture is a conjecture in mathematics that concerns a sequence
  13. defined as follows: start with any positive integer n. Then each term is obtained
  14. from the previous term as follows: if the previous term is even, the next term
  15. is one half the previous term. If the previous term is odd, the next term is 3
  16. times the previous term plus 1. The conjecture is that no matter what value of n,
  17. the sequence will always reach 1. */
  18. import java.util.ArrayList;
  19. public class LongestCollatzSequence {
  20. private long longestStartingNumber = this.findLongestCollatzSequence();
  21. public long getLongestStartingNumber() {
  22. return this.longestStartingNumber;
  23. }
  24. private ArrayList<Long> findCollatzSequenceForNum(long num) {
  25. // To contain the Collatz sequence
  26. ArrayList<Long> sequence = new ArrayList<Long>();
  27. // To add the starting number to the array
  28. sequence.add(num);
  29. while (num != 1) {
  30. // Number is even
  31. if (num % 2 == 0) {
  32. num = num / 2;
  33. sequence.add(num);
  34. }
  35. // Number is odd
  36. else {
  37. num = 3 * num + 1;
  38. sequence.add(num);
  39. }
  40. }
  41. /* Return the ArrayList containing the Collatz sequence for the
  42. specified number */
  43. return sequence;
  44. }
  45. private long findLongestCollatzSequence() {
  46. long largestStartingNumber = 0;
  47. long longestLength = 0;
  48. for (long i = 2; i <= 1000000; i++) {
  49. long collatzLength = this.findCollatzSequenceForNum(i).size();
  50. if (collatzLength > longestLength) {
  51. longestLength = collatzLength;
  52. largestStartingNumber = i;
  53. }
  54. else
  55. continue;
  56. }
  57. return largestStartingNumber;
  58. }
  59. }