%ProjectEuler/Octave/Problem4.m %Matthew Ellison % Created: %Modified: 03-28-19 %Find the largest palindrome made from the product of two 3-digit numbers %{ 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 . %} %Make your variables answer = 0; %For the product of the two numbers numbers = [100:999]; %Create an array with a list of all 3 digit numbers palindromes = []; %Holds all the numbers that are palindromes %Create 2 counters for an inner loop and an outer loop %This allows you to multiply 2 numbers from the same array outerCounter = 1; innerCounter = 1; %Start the timer startTime = clock(); while(outerCounter < size(numbers)(2)) innerCounter = outerCounter; %Once you have multiplied 2 numbers there is no need to multiply them again, so skip what has already been done while(innerCounter < size(numbers)(2)) %Multiply the two numbers answer = numbers(outerCounter) * numbers(innerCounter); %See if the number is a palindromes %%WARNING - Ocatave does not have a Reverse function. I had to create one that reversed strings if(num2str(answer) == Reverse(num2str(answer))) %Add it to the palindromes list palindromes(end + 1) = answer; end ++innerCounter; %Increment end ++outerCounter; %Increment end %Stop the timer endTime = clock(); %This is for timing purposes %Print the results printf("The largest palindrome made from the product of two 3-digit numbers is %d\n", max(palindromes)) printf("It took %f seconds to run this algorithm\n", etime(endTime, startTime)) %Cleanup your variables clear outerCounter; clear innerCounter; clear answer; clear numbers; clear palindromes; clear startTime; clear endTime; %{ Results: The largest palindrome made from the product of two 3-digit numbers is 906609 It took 663.732803 seconds to run this algorithm %} %This way is slow. I would like to find a faster way %{ The palindrome can be written as: abccba Which then simpifies to: 100000a + 10000b + 1000c + 100c + 10b + a And then: 100001a + 10010b + 1100c Factoring out 11, you get: 11(9091a + 910b + 100c) So the palindrome must be divisible by 11. Seeing as 11 is prime, at least one of the numbers must be divisible by 11 %}