What is the first triangle number to have more than 500 divisors?
Ok, this one kicked me in the pants, and it kicked my little Mac in the pants as well. I had to relearn how to get divisors quickly and efficiently, which meant seeking the wisdom of others on the Internet. But eventually I got a working program that didn't take all night to run.
function euler12
nn = 3;
while 1
if mod(nn,2) == 0
ndivisors = get_divisors(nn/2)*get_divisors(nn+1);
else
ndivisors = get_divisors((nn+1)/2)*get_divisors(nn);
end
if ndivisors > 500
break;
end
nn = nn+1;
end
nn
triangle_num = nn/2*(nn+1)
ndivisors
function ndivisors = get_divisors(nn)
ndivisors = 2; % 1 and nn
% Get the prime factors
vv = factor(nn);
nvv = length(vv);
ndivisors = ndivisors + length(unique(vv));
% Now get all the combinations of the prime factors
for ii = 2:(nvv-1)
aa = nchoosek(vv, ii);
bb = unique(aa, 'rows');
[mm, nn] = size(bb);
ndivisors = ndivisors + mm;
end