Project Euler #4 - Largest Palindrome Product in Java
Code
/*
* A palindromic number reads the same both ways. The largest palindrome
* made from the product of two 2-digit numbers is 9009 = 91 ×ばつ 99. Find the
* largest palindrome made from the product of two 3-digit numbers.
*/
public static int get4() {
int max = 1;
for (int i = 100; i < 999; i++) {
for (int j = i; j < 999; j++) {
int n = i * j;
int len = (int) Math.floor(Math.log10(n));
boolean ispalindrome = true;
for (int k = 0; k < 3; k++) {// 100^2=10^4,999^2=998001. 5-6
// digits middle atmax 3
int digitatk = (int) ((n % Math.pow(10, k + 1) - n
% Math.pow(10, k)) / Math.pow(10, k));
// eg. digit at 3 of 12345 =
// (12345%10^4-12345%10^3)/10^3=(2345-345)/10^3=2000/10^3=2
int l = len - k;
int digitatl = (int) ((n % Math.pow(10, l + 1) - n
% Math.pow(10, l)) / Math.pow(10, l));
if (digitatl != digitatk) {
ispalindrome = false;
}
}
if (ispalindrome && n > max) {
max = n;
}
}
}
return max;
}
Output:
Answer is 906609
Time taken 2.82342934 seconds
I am seeing that this is actually not in accord with the difficulty level said there. Firstly I cannot list all possible improvements it could have, so if you have any improvement help me. Current problems (not exhaustive):
- Time
- \${\mathcal O}(n^2)\$ where \$n=999\$ for looping only.
- Length checking method.
- Checking Palindrome.
- Digit Finding Method.
RE60K
- 1.5k
- 2
- 11
- 27
lang-java