-
Notifications
You must be signed in to change notification settings - Fork 0
/
Problem12.java
61 lines (53 loc) · 1.42 KB
/
Problem12.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
package com.javamultiplex.projecteuler;
import java.util.ArrayList;
import java.util.List;
/**
*
* @author Rohit Agarwal
* @category Project Euler Problems
* @Problem 12 - Highly divisible triangular number.
*
*/
public class Problem12 {
public static void main(String[] args) {
int target = 500;
long number = 1;
long triangularNumber = 0;
int count = 0;
while (true) {
/*
* Step 1: Find the triangular number.
*
* As triangular number is generated by adding natural numbers so
* Sum of first n natural number is = n(n+1)/2
*
*/
triangularNumber = (number) * (number + 1) / 2;
// Step 2: Get the number of divisors.
count = getCountofDivisors(triangularNumber);
// Step 3: If number of divisors > 500 then print it otherwise continue.
if (count > target) {
System.out.println("The value of the first triangle number to have over five hundred divisors :"
+ triangularNumber);
break;
}
number++;
}
}
private static int getCountofDivisors(long triangularNumber) {
long limit = (long) Math.sqrt(triangularNumber);
List<Long> list = new ArrayList<>();
long temp = 0;
for (long i = 1; i <= limit; i++) {
if (triangularNumber % i == 0) {
list.add(i);
temp = triangularNumber / i;
if (i != temp) {
list.add(temp);
}
}
}
int divisors = list.size();
return divisors;
}
}