To learn how to use Julia, I am running through the project Euler problems
(I had already solved most of them using other languages) and up to now,
they have all comfortably been solved under 1s without any clever
algorithm, even sometimes purposely brute forced.
However I am stuck on problem 23 (Find the sum of all the positive integers
which cannot be written as the sum of two abundant numbers.) which solves
in 8 s. The surprising thing to me is that what I assume to be the hard
part is solved in 0.1 s.
I have been struggling on and off for the last week but have gone nowhere.
I thought a fresh pair of eyes may see something.
Here is my code:
const maxAbundant = 28123
function sumOfDivisors(n::Int)
f = factor(n)
counter = 1
for i in keys(f)
count = 1
for j in 1:f[i]
count += i^j
end
counter *= count
end
counter-n
end
function isAbundant(n::Int)
sumOfDivisors(n) > n ? true : false
end
abundantNumbers=Array(Int,1)
abundantNumbers[1]=12
sizehint(abundantNumbers, maxAbundant)
for i = 13:maxAbundant
if isAbundant(i)
push!(abundantNumbers, i)
end
end
isSumOfAbundant=falses(1,maxAbundant)
tic()
for i = 1:length(abundantNumbers)
for j = i:length(abundantNumbers)
SumOfAbundant = abundantNumbers[i] + abundantNumbers[j]
if SumOfAbundant <= maxAbundant
isSumOfAbundant[SumOfAbundant]=true
else
break
end
end
end
toc()
result=0
for i = 1:maxAbundant
if !isSumOfAbundant[i]
result += i
end
end
result
When run with @time I get:
elapsed time: 7.967364175 seconds
elapsed time: 8.06121492 seconds (1359946448 bytes allocated, 18.32% gc
time)
So I am convinced the bit between tic() and toc() is not right and gc time
may be a clue but I really can't find why.
Any help will be greatly appreciated.
One thing I find annoying with Julia is that sometimes what seems to me a
very insignificant change in the code has dramatic effect in the execution
time. It is anyway a great tool to try things and find solutions quickly. I
wish I had had Julia when I started on Project Euler.
Thanks,
Arnaud