Skip to content

Instantly share code, notes, and snippets.

@janoulle
Created December 20, 2011 02:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save janoulle/1499904 to your computer and use it in GitHub Desktop.
Save janoulle/1499904 to your computer and use it in GitHub Desktop.
Problem 4 - Project Euler in Java by Jane Ullah
/**
*
* @author Jane Ullah
* @date 12/19/2011
* @purpose Solving Problem 4 from ProjectEuler.net
*
*/
public static void main(String[] args) {
/*if (isPalindrome(1222321)) {
System.out.println("Yes.");
}*/
boolean loopControl = false;
String palindrome = "";
for (int i = 1000000; !loopControl; i--) {
if (isPalindrome(i)) {
palindrome = valid3DigitDivisor(i);
if ( !(palindrome == "")) {
System.out.println("largest palindrome is: " + i);
loopControl = true;
}
}
}
}
//Method to test for palindromes; Separated out for ease of reading.
private static boolean isPalindrome(int number){
//converting the number to a String
String dummy = "" + number;
int index;
//Compares the ends of the String and terminates when a single mismatch is found
for (index = 1; index <= dummy.length()/2 && ( (dummy.charAt((dummy.length()-index)) == dummy.charAt((index-1)) ) ); index++);
return (index > dummy.length()/2);
}
//Method to check the palindrome's factors and select those that are 3 digit numbers
//Returns an empty string if no 3 digit numbers (whose product is the palindrome) were found.
private static String valid3DigitDivisor(int palindrome){
int j, loopControl = (int) Math.floor(Math.sqrt(palindrome));
String divisor, quotient, result = "";
for (j = 0; j <= loopControl; j++) {
//Catching divisors of the palindrome
if ( (palindrome % (j+2) == 0) ) {
divisor = "" + (j+2);
quotient = "" + (palindrome/(j+2));
//Selecting for numbers (divisor and quotient) that are 3 digits
if ( (divisor.length() == 3) && (quotient.length() == 3) ) {
result = divisor + " " + quotient;
}
}
}
return result;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment