Files
ProjectEulerOctave/Problem3.m

84 lines
2.6 KiB
Matlab

%ProjectEuler/Octave/Problem3.m
%Matthew Ellison
% Created:
%Modified: 03-28-19
%The largest prime factor of 600851475143
%{
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
number = 600851475143; %The number we are trying to find the greatest prime factor of
primeNums = []; %A list of prime numbers. Will include all prime numbers <= number
factors = []; %For the list of factors of number
tempNum = number; %Used to track the current value if all of the factors were taken out of number
%Get the prime numbers up to sqrt(number). If it is not prime there must be a value <= sqrt
primeNums = primes(sqrt(number));
%Start the timer
startTime = clock();
%Setup the loop
counter = 1;
%Start with the lowest number and work your way up. When you reach a number > size(primeNums) you have found all of the factors
while(counter <= size(primeNums)(2))
%Divide the number by the next prime number in the list
answer = (tempNum/primeNums(counter));
%If it is a whole number add it to the factors
if(mod(answer,1) == 0)
factors(end + 1) = primeNums(counter);
%Set tempNum so that it reflects number/factors
tempNum = tempNum / primeNums(counter);
%Keep the counter where it is in case a factor appears more than once
%Get the new set of prime numbers
primeNums = primes(sqrt(tempNum));
else
%If it was not an integer increment the counter
++counter;
end
end
%When the last number is not divisible by a prime number it must be a prime number
factors(end + 1) = tempNum;
%Stop the timer
endTime = clock();
%Print the results
printf("The largest prime factor of 600851475143 is %d\n", max(factors))
printf("It took %f seconds to run this algorithm\n", etime(endTime, startTime))
%Cleanup your variables
clear counter;
clear tempNum;
clear answer;
clear number;
clear primeNums;
clear factors;
clear startTime;
clear endTime;
clear ans;
%{
Results:
The largest prime factor of 600851475143 is 6857
It took 0.006256 seconds to run this algorithm
%}