Skip to content

Instantly share code, notes, and snippets.

@cupofcat
Created November 18, 2011 00:18
Show Gist options
  • Save cupofcat/1375069 to your computer and use it in GitHub Desktop.
Save cupofcat/1375069 to your computer and use it in GitHub Desktop.
A very naive Java program finding the smallest Lychrel number
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