Created
November 18, 2011 00:18
-
-
Save cupofcat/1375069 to your computer and use it in GitHub Desktop.
A very naive Java program finding the smallest Lychrel number
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class LychrelLibrary { | |
public static String reverseString(String string) { | |
return new StringBuffer(string).reverse().toString(); | |
} | |
public static long reverseNumber(long n) { | |
return Long.valueOf(reverseString(String.valueOf(n))); | |
} | |
/** | |
* This is in a way a halting problem. Our best estimation | |
* is checking for each number for as long as we can, and | |
* if we overflow long then we assume it's a Lychrel number | |
* (although it might not be!) | |
* | |
* @return a smallest number we think might be a Lychrel | |
*/ | |
public static long findSmallestLychrel() { | |
long candidate = 0; | |
while (true) { | |
if (mightBeALychrelNumber(candidate)) | |
return candidate; | |
candidate++; | |
} | |
} | |
public static boolean mightBeALychrelNumber(long number) { | |
// If the long overfloats we have no chance of finding | |
// the palindrome, so it is an indication that | |
// the number might be a Lychrel number | |
while (number >= 0) { | |
number += reverseNumber(number); | |
if (isPalindrome(number)) | |
return false; | |
} | |
return true; | |
} | |
public static boolean isPalindrome(long number) { | |
String numberAsString = String.valueOf(number); | |
return numberAsString.equals(reverseString(numberAsString)); | |
} | |
public static void main(String[] args) { | |
System.out.println(findSmallestLychrel()); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment