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?
function getNumberOfDivisors(n::UInt64)
# using sqrt to reduce number of operations by half
divisors::UInt64 = 0;
for i in 1:1:(sqrt(n))
if n%i == 0
divisors +=2;
end
end
if sqrt(n)^2 == n
divisors -=1;
end
return divisors
end
function getNumber(N::UInt64)
currDivisors::UInt64 = 0;
currNumber::UInt64 = 0;
i::UInt64 = 1;
while currDivisors <= N
currNumber += i;
i += 1;
currDivisors = getNumberOfDivisors(currNumber);
end
return currNumber
end
function parseARGS()
if isempty(ARGS)
numberOfDivisors::UInt64 = 500;
else
numberOfDivisors = tryparse(UInt64,ARGS[1]);
end
return numberOfDivisors
end
function main()
numberOfDivisors::UInt64 = parseARGS();
firstTriangleNumberBelowThreshold = getNumber(numberOfDivisors);
println(firstTriangleNumberBelowThreshold)
end
main()
$ julia ProjectEuler0012.jl 5
28
0.000067 seconds (17 allocations: 912 bytes)
$ julia ProjectEuler0012.jl 10
120
0.000065 seconds (17 allocations: 912 bytes)
$ julia ProjectEuler0012.jl 50
25200
0.000952 seconds (19 allocations: 944 bytes)
$ julia ProjectEuler0012.jl 100
73920
0.003015 seconds (19 allocations: 944 bytes)
$ julia ProjectEuler0012.jl 250
2162160
0.085168 seconds (19 allocations: 944 bytes)
$ julia ProjectEuler0012.jl 500
76576500
3.157186 seconds (19 allocations: 944 bytes)
Brute forcing it is too slow! Perhaps there is some clever way to solve this using prime factorization.