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
. The factors contained in the first four triangle numbers are:
1: 1
3: 1, 3
6: 1, 2, 3, 6
10: 1, 2, 5, 10
We see that 6
is the first triangle number to have over four divisors.
In order to find the first triangle number with over 500 divisors, I wrote the following code:
s1=0;
s2=0;
A=zeros(1,2);
for i=1:4000
s1=i+s1;
s2=0;
for n=1:s1
if rem(s1,n)==0
s2=s2+1;
end
end
if s2>=500
A=[s1 s2];
disp(A)
end
end
I would like to speed up this code using parfor
instead of for
on the outer loop. However, I get the error:
Error: The variable s1 is perhaps intended as a reduction variable, but is actually an uninitialized temporary.
See Parallel for Loops in MATLAB, "Temporary Variables Intended as Reduction Variables".
How can I parallellise this code?