Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class Euler{
- public static void main(String[] args){
- int currentA = 100;
- int currentB = 100;
- int product = 0;
- int finalProduct = 0;
- //loops through currentA and currentB for values 100-999. I wanted to use currentA and currentB in the for loops, but I got a "duplicate local variable" exception
- for(int currentA1 = 100; currentA1 <= 999; currentA1++){
- for(int currentB1 = 100; currentB1 <= 999; currentB1++){
- //Calculates the product, passes the product to inPalindrome, and records the largest palindrome product
- product = currentA * currentB;
- if(isPalindrome(product) && product > finalProduct){
- finalProduct = product;
- }
- currentB++;
- }
- currentA++;
- }
- //Prints the final answer.
- System.out.printf("The answer is %d.", finalProduct);
- }
- //Checks if an integer is a palindrome
- public static boolean isPalindrome(int candidate){
- int hunThous = 0;
- int tenThous = 0;
- int thous = 0;
- int huns = 0;
- int tens = 0;
- int ones = 0;
- int which = 0;
- //Sets variables equal to individual digits for 5-digit numbers.
- if(candidate >= 10_000 && candidate <= 99_999){
- tenThous = candidate / 10000;
- thous = candidate % 10000 / 1000;
- huns = candidate % 1000 / 100;
- tens = candidate % 100 / 10;
- ones = candidate % 10;
- which = 1;
- //Sets variables equal to individual digits for 6-digit numbers.
- }else if(candidate >= 100_000 && candidate <= 999_999){
- hunThous = candidate / 100_000;
- tenThous = candidate % 100_000 / 10000;
- thous = candidate % 10000 / 1000;
- huns = candidate % 1000 / 100;
- tens = candidate % 100 / 10;
- ones = candidate % 10;
- which = 2;
- }else{
- System.out.println("Error. Product not within range: 10,000 - 999,999.");
- }
- //Checks to see if opposite digits match. Palindromes will have matching opposite digits.
- if(which == 1 && tenThous == ones && thous == tens){
- return true;
- }else if(which == 2 && hunThous == ones && tenThous == tens && thous == huns){
- return true;
- }else{
- return false;
- }
- }
- }
Add Comment
Please, Sign In to add comment