mirror of
https://bitbucket.org/Mattrixwv/projecteuleroctave.git
synced 2025-12-06 17:43:57 -05:00
Initial commit with existing files
This commit is contained in:
80
Problem14.m
Normal file
80
Problem14.m
Normal file
@@ -0,0 +1,80 @@
|
||||
%ProjectEuler/Octave/Problem14.m
|
||||
%Matthew Ellison
|
||||
% Created:
|
||||
%Modified: 03-28-19
|
||||
%This is a script to answer Problem 14 for Project Euler
|
||||
%{
|
||||
The following iterative sequence is defined for the set of positive integers:
|
||||
n → n/2 (n is even)
|
||||
n → 3n + 1 (n is odd)
|
||||
Which starting number, under one million, produces the longest chain?
|
||||
%}
|
||||
%{
|
||||
Copyright (C) 2019 Matthew Ellison
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU Lesser General Public License as published by
|
||||
the Free Software Foundation, either version 3 of the License, or
|
||||
(at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU Lesser General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Lesser General Public License
|
||||
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
%}
|
||||
|
||||
|
||||
%Setup your variables
|
||||
currentLength = 0;
|
||||
maxLength = 0;
|
||||
currentNum = 1;
|
||||
maxNum = 0;
|
||||
|
||||
%Start the timer
|
||||
startTime = clock();
|
||||
|
||||
%Step through every number less than 1000000
|
||||
while(currentNum < 1000000)
|
||||
currentLength = 0;
|
||||
workingNum = currentNum; %So you can do math on the current number
|
||||
while(workingNum > 1)
|
||||
if(mod(workingNum, 2) == 0)
|
||||
workingNum = workingNum / 2;
|
||||
else
|
||||
workingNum = (3 * workingNum) + 1;
|
||||
end
|
||||
++currentLength;
|
||||
end
|
||||
%If the current number has a longer chain than the current max it becomes the max
|
||||
if(currentLength > maxLength)
|
||||
maxLength = currentLength;
|
||||
maxNum = currentNum;
|
||||
end
|
||||
++currentNum;
|
||||
end
|
||||
|
||||
%Stop the timer
|
||||
endTime = clock();
|
||||
|
||||
%Print the results
|
||||
printf("The longest chain with a starting number < 1000000 is %d with a length of %d\n", maxNum, maxLength)
|
||||
printf("It took %f seconds to run this algorithm\n", etime(endTime, startTime))
|
||||
|
||||
%Cleanup the variables
|
||||
clear maxLength;
|
||||
clear maxNum;
|
||||
clear endTime;
|
||||
clear startTime;
|
||||
clear currentNum;
|
||||
clear currentLength;
|
||||
clear workingNum;
|
||||
clear ans;
|
||||
|
||||
%{
|
||||
Results:
|
||||
The longest chain with a starting number < 1000000 is 837799 with a length of 524
|
||||
It took 1136.180946 seconds to run this algorithm
|
||||
%}
|
||||
Reference in New Issue
Block a user