-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy patheuler012.js
More file actions
72 lines (56 loc) · 2.12 KB
/
Copy patheuler012.js
File metadata and controls
72 lines (56 loc) · 2.12 KB
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
62
63
64
65
66
67
68
69
70
71
72
// 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?
console.log(TriangleNumbers())
function TriangleNumbers () {
for (i=1; true; i++) {
// algorithm for generating trianglular numbers:
var Tn = i*(i+1)*0.5
var number = Tn;
// p is lowest prime
var p = 2;
primeFactors = []
// prime factorisation of each triangular number
while (Tn >= p*p) {
if (Tn%p == 0) {
Tn = Tn/p
primeFactors.push(p)
} else {
p++
}
}
primeFactors.push(Tn)
var exponent = 1;
var exponentsArray = [];
// multiplication principle, the number of divisors is equal to the product of all (exponents of prime factors +1)
// e.g. Divisors of number 496 = 2^4 * 31
// (4+1) * (1+1) = 10 divisors
// 1,2,4,8,16,31,62,124,248,496
for (j=0; j<primeFactors.length; j++) {
if (primeFactors[j] == primeFactors[j+1]) {
exponent++
} else {
exponentsArray.push(exponent+1) // dont forget the +1
exponent = 1;
}
}
var divisors = 1;
for (k=0; k<exponentsArray.length; k++) {
divisors = divisors * exponentsArray[k];
}
// check when a number goes over 500 divisors
if (divisors >= 500) {
return number;
}
}
}
// note to self, read the question. I initially was confused as to why the solution was taking so long, until I re-read and saw it was OVER 500, not EXACTLY 500 divisors.