Skip to content

Commit 2f2e944

Browse files
authored
Create Problem12.java
Added solution for problem 12 of Project Euler
1 parent d0962bc commit 2f2e944

File tree

1 file changed

+63
-0
lines changed

1 file changed

+63
-0
lines changed

ProjectEuler/Problem12.java

Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
1+
/*
2+
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.
3+
The first ten terms would be:
4+
5+
1, 3, 6, 10, 15, 21, 28, 36, 45, 55, ...
6+
7+
Let us list the factors of the first seven triangle numbers:
8+
9+
1: 1
10+
3: 1,3
11+
6: 1,2,3,6
12+
10: 1,2,5,10
13+
15: 1,3,5,15
14+
21: 1,3,7,21
15+
28: 1,2,4,7,14,28
16+
We can see that 28 is the first triangle number to have over five divisors.
17+
18+
What is the value of the first triangle number to have over five hundred divisors?
19+
*/
20+
21+
public class Problem_12_Highly_Divisible_Triangular_Number {
22+
23+
/* returns the nth triangle number; that is, the sum of all the natural numbers less than, or equal to, n */
24+
public static int triangleNumber(int n) {
25+
int sum = 0;
26+
for (int i = 0; i <= n; i++)
27+
sum += i;
28+
return sum;
29+
}
30+
31+
public static void main(String[] args) {
32+
33+
long start = System.currentTimeMillis(); // start the stopwatch
34+
35+
int j = 0; // j represents the jth triangle number
36+
int n = 0; // n represents the triangle number corresponding to j
37+
int numberOfDivisors = 0; // number of divisors for triangle number n
38+
39+
while (numberOfDivisors <= 500) {
40+
41+
// resets numberOfDivisors because it's now checking a new triangle number
42+
// and also sets n to be the next triangle number
43+
numberOfDivisors = 0;
44+
j++;
45+
n = triangleNumber(j);
46+
47+
// for every number from 1 to the square root of this triangle number,
48+
// count the number of divisors
49+
for (int i = 1; i <= Math.sqrt(n); i++)
50+
if (n % i == 0)
51+
numberOfDivisors++;
52+
53+
// 1 to the square root of the number holds exactly half of the divisors
54+
// so multiply it by 2 to include the other corresponding half
55+
numberOfDivisors *= 2;
56+
}
57+
58+
long finish = System.currentTimeMillis(); // stop the stopwatch
59+
60+
System.out.println(n);
61+
System.out.println("Time taken: " + (finish - start) + " milliseconds");
62+
}
63+
}

0 commit comments

Comments
 (0)