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
None of the above seemed to have given the right answer. (I think the logic may be correct but the right answer is 906609). Since you are not aware that the number is 6 digit or 5 digit, you want to check which both. Below is a simple code to do same.
The multiplication is called once to often, I know...
i = 999
for u in range (100,1000):
for y in range (100,1000):
if len(str(u*y)) == 5 and str(u*y)[0]==str(u*y)[4]and str(u*y)[1]==str(u*y)[3] and u*y>i:
i=u*y
print ('the product of ', u, ' and ',y,' is: ',u*y)
elif len(str(u*y)) == 6 and str(u*y)[0]==str(u*y)[5]and str(u*y)[1]==str(u*y)[4]and str(u*y)[2]==str(u*y)[3]and u*y>i:
i=u*y
print ('the product of ', u, ' and ',y,' is: ',u*y)
Done in C. This might help you.
#include<stdio.h>
int calculate(int n)
{
int temp = 0,m = 0;
m = n;
while(n != 0)
{
temp = temp * 10;
temp = temp + n % 10;
n = n / 10;
}
if(m == temp)
{
printf(" %d \n",temp);
return temp;
}
else
{
return 0;
}
}
int main()
{
int i,j,temp = 0,count=0,temp1 = 0;
for(i = 100;i < 1000;i++)
{
for(j = 100;j < 1000;j++)
{
temp1 = i * j;
temp = calculate(temp1);
if(temp > count)
{
count = temp;
}
}
}
printf(" The Largest Palindrome number is : %d \n",count);
}
You are iterating for loop with number from 998001 to 10000 in that some number may not be a product two 3-digit number.
You for should multiply two 3-digit number and than compare it if that number is palindrome or not.
Your for loop code should be :
for(int i=999;i>=100;i--)
{
int k = i-1;
int product = i * k;
System.out.println(i+" * "+k+" = "+product);
if(isPalindrome(product)==true){
System.out.println("palindrum number "+product);
System.out.println("Product of : "+i+" * "+k);
break;
}
}
This will gives you largest palindrome number of which is product of two 3-digit number.
Output is :
palindrum number 289982
Product of : 539 * 538
This will true if both number is different while you multiply.
If you want to include same number product to check that is palindrome or not than there may be little change in above code.
For that code should be :
for(int i=999;i>=100;i--){
int k = i;
int product = i * k;
System.out.println(i+" * "+k+" = "+product);
if(isPalindrome(product)==true){
System.out.println("palindrum number "+product);
System.out.println("Product of : "+i+" * "+k);
break;
}
else{
k = i - 1;
product = i * k;
System.out.println(i+" * "+k+" = "+product);
if(isPalindrome(product)==true){
System.out.println("palindrum number "+product);
System.out.println("Product of : "+i+" * "+k);
break;
}
}
}
Which give you output like :
palindrum number 698896
Product of : 836 * 836
I think this is what you need to do.
/* Find the largest palindrome made from the product of two n-digit numbers. Since the result could be very large, you should return the largest palindrome mod 1337. Example: Input: 2 Output: 987 Explanation: 99 x 91 = 9009, 9009 % 1337 = 987 Note: The range of n is [1,8]. */
public class LargestPalindromeProduct {
public int largestPalindrome(int n) {
if(n<1 || n>8)
throw new IllegalArgumentException("n should be in the range [1,8]");
int start = (int)Math.pow(10, n-1); // n = 1, start 1, end = 10 -1. n = 2, start = 10, end = 99;
if(start == 1) start = 0 ; // n = 3, start = 100, end == 999
int end = (int)Math.pow(10, n) - 1;
long product = 0;
long maxPalindrome = 0;
for(int i = end ; i >= start ; i--)
{
for(int j = i ; j >= start ; j--)
{
product = i * j ;
// if one of the number is modulo 10, product can never be palindrome, e.g 100 * 200 = 200000, or 240*123 = 29520. this is because the product will always end with zero but it can never begin with zero except one/both of them numbers is zero.
if(product % 10 == 0)
continue;
if(isPalindrome(product) && product > maxPalindrome)
maxPalindrome = product;
}
}
return (int)(maxPalindrome % 1337);
}
public static boolean isPalindrome(long n){
StringBuffer sb = new StringBuffer().append(Long.toString(n)).reverse();
if(sb.toString().equals(Long.toString(n)))
return true;
return false;
}
public static void main(String[] args){
System.out.println(new LargestPalindromeProduct().largestPalindrome(2));
}
}
This method is significantly faster than previous methods. It starts by evaluating 999 * 999. It is an implementation of the method proposed in Puzzled over palindromic product problem
We would like to try larger products before smaller products, so next try 998 * 998, with the outer loop decreasing by one each time. In the inner loop, take the outer limit number to create (n+y)(n-y) (which is always less than n^2), iterating over y until one of the factors is too large or too small.
From https://pthree.org/2007/09/15/largest-palindromic-number-in-python/, one of the factors must be a multiple of 11. Check to see if one of the factors is a multiple of 11 and that the product is greater than the previously found (or initial) palindromic number.
Once these tests are satisfied, see if the product is a palindrome.
Once a palindrome is found, we can raise the limit on the outer loop to the square root of the palindrome, since that is the minimum value that could possibly be an answer.
This algorithm found the answer in only 475 comparisons. This is far better than 810,000 proposed by the simple methods, or even 405450.
Can anyone propose a faster method?
Longest palindromes:
Max factor Max Palindrome
9999 99000099
99999 9966006699
999999 999000000999
9999999 99956644665999
99999999 9999000000009999
999999999 999900665566009999
public class LargestPalindromicNumberInRange {
private final long lowerLimit;
private final long upperLimit;
private long largestPalindrome;
private long largestFirstFactor;
private long largestSecondFactor;
private long loopCount;
private long answerCount;
public static void main(String[] args) {
long lowerLimit = 1000;
long upperLimit = 9999;
LargestPalindromicNumberInRange palindromicNumbers =
new LargestPalindromicNumberInRange(lowerLimit, upperLimit);
palindromicNumbers.TopDown();
}
private LargestPalindromicNumberInRange(long lowerLimit, long upperLimit){
this.lowerLimit = lowerLimit;
this.upperLimit = upperLimit;
}
private void TopDown() {
loopCount = 0;
answerCount = 0;
largestPalindrome = lowerLimit * lowerLimit;
long initialLargestPalindrome = largestPalindrome;
long lowerFactorLimit = lowerLimit;
for (long limit = upperLimit; limit > lowerFactorLimit; limit--){
for (long firstFactorValue = limit; firstFactorValue >= limit - 1; firstFactorValue--) {
long firstFactor = firstFactorValue;
long secondFactor = limit;
while(secondFactor <= upperLimit && firstFactor >= lowerLimit){
if (firstFactor % 11 == 0 || secondFactor % 11 == 0) {
long product = firstFactor * secondFactor;
if (product < largestPalindrome) { break; }
loopCount++;
if (IsPalindromic(product)) {
// System.out.print("Answer: " + product + "\n");
answerCount++;
largestPalindrome = product;
largestFirstFactor = firstFactor;
largestSecondFactor = secondFactor;
lowerFactorLimit = (long) Math.sqrt(largestPalindrome);
break;
}
}
firstFactor--;
secondFactor++;
}
}
System.out.print("Answer: " + largestPalindrome + "\n");
System.out.print("Factor1: " + largestFirstFactor + "\n");
System.out.print("Factor2: " + largestSecondFactor + "\n");
System.out.print("Loop count: " + loopCount + "\n");
System.out.print("Answer count: " + answerCount + "\n");
}
private boolean IsPalindromic(Long x) {
String forwardString = x.toString();
StringBuilder builder = new StringBuilder();
builder.append(forwardString);
builder = builder.reverse();
String reverseString = builder.toString();
return forwardString.equals(reverseString);
}
}
public class LargestPalindromProduct {
public static void main(String args[]) {
LargestPalindromProduct obj = new LargestPalindromProduct();
System.out.println("The largest palindrome for product of two 3-digit numbers is " + obj.getLargestPalindromeProduct(3));
}
/*
* @param digits
* @return
*/
private int getLargestPalindromeProduct(int digits) {
int largestPalindromeProduct = -1;
int startNum = (int)Math.pow(10, digits) - 1;
int endNum = (int)Math.pow(10, digits-1) - 1;
for (int i = startNum; i > endNum; i--) {
for (int j = startNum; j > endNum; j--) {
if (isPalindrome(i * j)) {
largestPalindromeProduct = Math.max(largestPalindromeProduct, i * j);
}
}
}
return largestPalindromeProduct;
}
private boolean isPalindrome(int number) {
String s = String.valueOf(number);
for (int i = 0, j = s.length() -1; i < j;i++, j--) {
if (s.charAt(i) != s.charAt(j)) {
return false;
}
}
return true;
}