I was trying to solve project Euler problem 4 which is:
A palindromic number reads the same both ways. The largest palindrome made from the product of tw
Here is the Python code for the Project_Euler-4 problem.
We have to find the largest palindrome number which is a product of two three digit numbers
import math
def isPal(x):
x=str(x)
t=x[::-1]
if(x==t):
return True
else:
return False
max=0
for i in range(999,99,-1):
for j in range(999,99,-1):
if(isPal(i*j)):
if((i*j)>max):
max=(i*j)
print(max)
The answer will be 906609
The for loop runs for i
from 998001 down to 100000. Nowhere in your program are you checking that i
can actually be the product of two 3-digit numbers.
Well I am seeing a lot of things wrong here.
And I am seeing a correct code already posted by a user (ROMANIA)
Here is a solution that doesn't iterate through all the 6-digit numbers:
public static boolean isPalindrome(int nr) {
int rev = 0; // the reversed number
int x = nr; // store the default value (it will be changed)
while (x > 0) {
rev = 10 * rev + x % 10;
x /= 10;
}
return nr == rev; // returns true if the number is palindrome
}
public static void main(String[] args) {
int max = -1;
for ( int i = 999 ; i >= 100 ; i--) {
for (int j = 999 ; j >= 100 ; j-- ) {
int p = i * j;
if ( max < p && isPalindrome(p) ) {
max = p;
}
}
}
System.out.println(max > -1? max : "No palindrome found");
}
Edit:
An improved solution for the main
method ( according to Peter Schuetze ) could be:
public static void main(String[] args) {
int max = -1;
for ( int i = 999 ; i >= 100 ; i--) {
if ( max >= i*999 ) {
break;
}
for (int j = 999 ; j >= i ; j-- ) {
int p = i * j;
if ( max < p && isPalindrome(p) ) {
max = p;
}
}
}
System.out.println(max > -1? max : "No palindrome found");
}
For this particular example, the time is about 2 times better, but if you have bigger numbers, the improvement will be more significant.
Output:
906609
You are decrementing i sequentially from 999*999 to 100 *100. It does not necessarily mean that the first palindrome you are finding is a product of two 3 digit numbers.
The palindrome 997799 has 11 and 90709 as prime factors which is not a product of two 3 digit numbers.
#include <iostream>
using namespace std;
int reverse(int a){
int reverse=0;
for(int i=0;i<6;i++){
reverse = reverse*10+a%10;
a/=10;
}
return reverse;
}
int main(){
int a=999,max=1,rev;;
int b=999;
for(a=999;a>100;a--){
for(b=999;b>100;b--){
int p = a*b;
rev = reverse(p);
if (p==rev) {
if(max<rev){
max = rev;
}
}
}
}
cout<<"\n"<<max<<"\n";
return 0;
}