Files
OctaveFunctions/ProjectEuler/Problem3.m

48 lines
1.6 KiB
Matlab

%ProjectEuler/Problem3.m
%This is a script to answer Problem 3 for Project Euler
%The largest prime factor of 600851475143
%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
%number = 16; %Used for a test case
%Get the prime numbers up to sqrt(number). If it is not prime there must be a value <= sqrt
primeNums = primes(sqrt(number));
%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;
%Remove the variables
clear counter;
clear tempNum;
clear answer;
clear number;
clear primeNums;
%Print the answer
max(factors)