1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253 |
- /* The sequence of triangle numbers is generated by adding the natural numbers.
- So the 7th triangle number would be 1 + 2 + 3 + 4 + 5 + 6 + 7 = 28.
- The first ten terms would be:
- 1, 3, 6, 10, 15, 21, 28, 36, 45, 55, ...
- Let us list the factors of the first seven triangle numbers:
- 1: 1
- 3: 1,3
- 6: 1,2,3,6
- 10: 1,2,5,10
- 15: 1,3,5,15
- 21: 1,3,7,21
- 28: 1,2,4,7,14,28
- We can see that 28 is the first triangle number to have over five divisors.
- What is the value of the first triangle number to have over five-hundred
- divisors? */
- import java.util.ArrayList;
- public class HighlyDivisibleTriangularNumber {
- private static ArrayList<Long> divisors = new ArrayList<Long>();
- public static ArrayList<Long> getAllTriangleNumDivisors(long triangleNum) {
- // To contain all the divisors for the specified triangle number
- ArrayList<Long> divisors = new ArrayList<>();
- // To find all the divisors for the specified triangle number
- for (long i = 1; i <= triangleNum; i++) {
- if (triangleNum % i == 0)
- divisors.add(i);
- }
- // To return the ArrayList of divisors for the specified triangle number
- return divisors;
- }
- public static long calculateTriangleNumber() {
- long num = 0;
- long iterator = 0;
- while (divisors.size() <= 500) {
- iterator++;
- num += iterator;
- divisors = getAllTriangleNumDivisors(num);
- }
- return num;
- }
- }
|