function [] = Problem28() %ProjectEuler/Octave/Problem28.m %Matthew Ellison % Created: 09-29-19 %Modified: 10-06-19 %Find the product of the coefficients, |a| < 1000 and |b| <= 1000, for the quadratic expression that produces the maximum number of primes for consecutive values of n, starting with n=0. %{ 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 . %} %Setup the variables finalLocation = false; %A flag to indicate if the final location to be filled has been reached currentNum = 1; %Set the number that is going to be put at each location %Make a 1001x1001 grid full of 0's square = zeros(1001, 1001); %Start the timer startTime = clock(); %Start with the middle location and set it correctly and advance the tracker to the next number xLocation = 501; yLocation = 501; square(yLocation, xLocation) = currentNum++; %Move right the first time ++xLocation; %Move in a circular pattern until you reach the final location while(~finalLocation) %Move down until you reach a blank location on the left while(square(yLocation, xLocation - 1) ~= 0) square(yLocation, xLocation) = currentNum++; ++yLocation; end %Move left until you reach a blank location above while(square(yLocation - 1, xLocation) ~= 0) square(yLocation, xLocation) = currentNum++; --xLocation; end %Move up until you reach a blank location to the right while(square(yLocation, xLocation + 1) ~= 0) square(yLocation, xLocation) = currentNum++; --yLocation; end %Move right until you reach a blank location below while(square(yLocation + 1, xLocation) ~= 0) square(yLocation, xLocation) = currentNum++; ++xLocation; %Check if you are at the final location and break the loop if you are if(xLocation > size(square)(2)) finalLocation = true; break; end end end %Get the sum of the diagonals sumOfDiag = 0; leftSide = 1; rightSide = size(square)(2); row = 1; while(row <= size(square)(2)) %This ensure the middle location is only counted one if(leftSide == rightSide) sumOfDiag += square(row, leftSide); else sumOfDiag += square(row, leftSide); sumOfDiag += square(row, rightSide); end ++row; ++leftSide; --rightSide; end %Stop the timer endTime = clock(); %Print the results printf("The sum of the diagonals in the given grid is %d\n", sumOfDiag); printf("It took %f to run this algorithm\n", etime(endTime, startTime)); end %{ Results: The sum of the diagonals in the given grid is 669171001 It took 8.751038 to run this algorithm %}