-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathproblem012.m
More file actions
71 lines (67 loc) · 2.13 KB
/
problem012.m
File metadata and controls
71 lines (67 loc) · 2.13 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
function N = problem012(P)
%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.
%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 (or P in general)divisors?
% The sub-function no_of_factors_S is defined.The function below_primes
% should be defined in the directory.
n = 1;
p1 = 1;%no_of_factors(n); here n = 1
p2 = 2;%no_of_factors(n+1);
p = p1*p2/2;% a0 is 1 here. The original formula is p = p1*p2*a0/(a0+1)
Prim = primes_to_n(100000);% Matrix B will be having all primes required for calculation.
while p < P
if rem(n,2) == 0
n_temp = n;
else
n_temp = n+1;
end
a0 = 0;
while rem(n_temp,2) == 0
n_temp = n_temp/2;
a0 = a0+1;
end
p = p1*p2*a0/(a0+1);
%keyboard
n = n+1;
p1 = p2;
p2 = no_of_factors_S(n+1,Prim);
end
%by the time it comes out the the value of n changes to n+1 and hence the
%final ans will be
N = n*(n-1)/2;
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%defining subfunction no_of_factors_S%%%%%%%%%%%%%
%The function below_primes should be defined in the domain
function s = no_of_factors_S(n,Prim)
% This function returns the no of all the possible factors of the given no
% including 1 and that no itself.
%The function prime_factors.m should be defined in the directory
B = Prim;
k = n;
i = 1;j=1;
A = [ ];
am = 1;
s = 1; p = 1;
while k > 1
if rem(k, B(1,i)) == 0%start of first if look
if j == 1
A = B(1,i);
j = 0;
k = k / B(1,i);
continue
end
k = k / B(1,i);
if B(1,i) ~= A(1,am)
s = s*(p+1);
p = 1;
A = [ A B(1,i)];
am = am+1;
else
p = p + 1;
end
else%else corresponding to first if
i = i + 1;
end
end
s = s*(p+1);% this step is for last iteration.