//ProjectEuler/Java/Problem4.java //Matthew Ellison // Created: 03-01-19 //Modified: 03-28-19 //Find the largest palindrome made from the product of two 3-digit numbers //Unless otherwise listed all non-standard includes are my own creation and available from https://bibucket.org/Mattrixwv/JavaClasses /* 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 . */ import mattrixwv.Stopwatch; import mattrixwv.Algorithms; import java.util.ArrayList; import java.util.Collections; public class Problem4{ private static final Integer START_NUM = 100; //The first number to be multiplied private static final Integer END_NUM = 999; //THe last number to be multiplied public static void main(String[] argv){ Stopwatch timer = new Stopwatch(); //To time the execution time of this algorithm //Start the timer timer.start(); ArrayList palindromes = new ArrayList(); //Start at the first 3-digit number and check every one up to the last 3-digit number for(Integer firstNum = START_NUM;firstNum <= END_NUM;++firstNum){ //You can start at the locatio of the first number because everything before that has already been tested. (100 * 101 == 101*100) for(Integer secondNum = firstNum;secondNum < END_NUM;++secondNum){ //Get the product Integer product = firstNum * secondNum; //Change the number into a string String productString = product.toString(); //Reverse the string String reverseString = new StringBuilder(productString).reverse().toString(); //If the number and it's reverse are the same it is a palindrome so add it to the list if(productString.equals(reverseString)){ palindromes.add(product); } else{ //System.out.println("ProductString = " + productString); //System.out.println("reverseString = " + reverseString); } //If it's not a palindrome ignore it and move to the next number } } //Stop the timer timer.stop(); //Sort the palindromes so that the last one is the largest Collections.sort(palindromes); //Print the results System.out.printf("The largest palindrome is %d\n", palindromes.get(palindromes.size() - 1)); System.out.printf("It took " + timer.getStr() + " to run this algorithm\n"); } } /* Results: The largest palindrome is 906609 It took 105.376 milliseconds to run this algorithm */