Skip to content

Instantly share code, notes, and snippets.

@belichuk
Created June 11, 2018 09:10
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 belichuk/672683085f510f7c772cf5ee75160b36 to your computer and use it in GitHub Desktop.
Save belichuk/672683085f510f7c772cf5ee75160b36 to your computer and use it in GitHub Desktop.
Find all palindromes made from the product of two 4-digit numbers ( Java )
package com.pal;
import java.io.File;
import java.io.FileOutputStream;
public class Main {
public static void main(String[] args) throws Exception {
File file = new File("output.txt");
file.createNewFile();
FileOutputStream fileOutputStream = new FileOutputStream("output.txt");
StringBuilder stringBuilder = new StringBuilder();
for (int i = 1000; i <= 9999; i++) {
if (i % 10 == 0) continue;
for (int j = i; j <= 9999; j++) {
if (j % 10 != 0 ) {
int k = i * j;
if (isPalindromeEx(k)) {
stringBuilder.append(i).append(' ').append(j).append(' ').append(k).append('\n');
}
}
}
}
fileOutputStream.write(stringBuilder.toString().getBytes());
fileOutputStream.close();
}
public static boolean isPalindrome(int number) {
int reversed = 0;
int original = number, remind;
while (number != 0) {
remind = number % 10;
reversed = reversed * 10 + remind;
number /= 10;
}
return reversed == original;
}
public static boolean isPalindromeEx(int number) {
int div = 10000000;
if (number < 10000000) {
div = 1000000;
}
int first = number / div;
int last = number % 10;
if (first != last) {
return false;
}
return isPalindrome(number);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment