-
Notifications
You must be signed in to change notification settings - Fork 1
/
CollatzConjecture.m
52 lines (44 loc) · 1005 Bytes
/
CollatzConjecture.m
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
%% Collatz
tic
set(0, 'DefaultAxesFontSize', 18);
set(0, 'DefaultFigureColor', 'w');
set(0,'defaultAxesFontName', 'serif')
%%
% collatzFun(670617279)
%%
% range of numbers being input into the collatz iteration
inputRange = 1024;
computationTime = zeros(1,inputRange);
for k = 1:inputRange
count = 0;
n = k;
while n ~= 1
count = count + 1;
n = collatzFun(n);
end
computationTime(k) = count;
end
cmap = 0.9*jet(inputRange);
[~,idx] = sort(computationTime,'ascend');
figure(1), clf
% scatter(1:inputRange, computationTime,[], cmap,'filled')
scatter(idx, computationTime(idx),[], cmap,'filled')
axis square
xlabel('input n')
ylabel('Collatz iteration counts')
grid on
powersOfTwo = 2.^(0:floor(log2(inputRange)));
hold on
plot(powersOfTwo, computationTime(powersOfTwo),'k-')
hold off
toc
% h = gca;
% h.XScale = 'log';
function n = collatzFun(n)
% function to execute a single collatz iteration
if mod(n,2) == 0
n = n/2;
else
n = 3*n + 1;
end
end