HighlyDivisibleTriangularNumber.java 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. /* The sequence of triangle numbers is generated by adding the natural numbers.
  2. So the 7th triangle number would be 1 + 2 + 3 + 4 + 5 + 6 + 7 = 28.
  3. The first ten terms would be:
  4. 1, 3, 6, 10, 15, 21, 28, 36, 45, 55, ...
  5. Let us list the factors of the first seven triangle numbers:
  6. 1: 1
  7. 3: 1,3
  8. 6: 1,2,3,6
  9. 10: 1,2,5,10
  10. 15: 1,3,5,15
  11. 21: 1,3,7,21
  12. 28: 1,2,4,7,14,28
  13. We can see that 28 is the first triangle number to have over five divisors.
  14. What is the value of the first triangle number to have over five-hundred
  15. divisors? */
  16. import java.util.ArrayList;
  17. public class HighlyDivisibleTriangularNumber {
  18. private static ArrayList<Long> divisors = new ArrayList<Long>();
  19. public static ArrayList<Long> getAllTriangleNumDivisors(long triangleNum) {
  20. // To contain all the divisors for the specified triangle number
  21. ArrayList<Long> divisors = new ArrayList<>();
  22. // To find all the divisors for the specified triangle number
  23. for (long i = 1; i <= triangleNum; i++) {
  24. if (triangleNum % i == 0)
  25. divisors.add(i);
  26. }
  27. // To return the ArrayList of divisors for the specified triangle number
  28. return divisors;
  29. }
  30. public static long calculateTriangleNumber() {
  31. long num = 0;
  32. long iterator = 0;
  33. while (divisors.size() <= 500) {
  34. iterator++;
  35. num += iterator;
  36. divisors = getAllTriangleNumDivisors(num);
  37. }
  38. return num;
  39. }
  40. }