Largest palindrome product - euler project

你说的曾经没有我的故事 提交于 2019-11-28 11:50:34

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.

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.

Yagnesh Agola

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.

You are also assuming that the first palindrome you'll find will be the largest. The first palindrome you'll find is 580085 which isn't the right answer.

You are also assuming that the first palindrome you'll find is the product of two 3 digit numbers. You should also use two different numbers instead of multiplying 999 with 999 and iterating down to 100 * 100.

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)
codewhywhat
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;
}

Well I am seeing a lot of things wrong here.

  • First of all you are using multiplication of 2 highest 3 digit numbers and then decrementing it to find palindrome. What you need to do according to question is to use variables having highest 3 digit no.s and then decrement them to check there resultant product.
  • Second for checking if the no. is palindrome you used an array to store it then used a loop to check it, I find it incorrect, as you could simply store the resultant no. in another integer variable by using the simple approach.(reverseNum * 10 + (num % 10) )

And I am seeing a correct code already posted by a user (ROMANIA)

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);
}

/* 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));
    }

}

Since no one did in R. This a solution that gives the answer to the problem.

Project Euler Question 4

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. R doesn't have a built-in function to check palindromes so I created one although 'rev' can be used :). Also, the code is not optimized for speed on purpose primarily to increase readability.

       reverse <- function(x){
        Args:
       x : object whose elements are to be reversed, can be of type 
       'character' or 'vector' of length = 1
       Returns:
          x : The object's elements are reversed e.g boy becomes yob and 23 
       becomes 32
       Error Handling:
      if (is.vector(x) == TRUE & length(x) > 1){
        stop("Object whose length > 1 cannot be used with reverse(x) 
        consider vector.reverse(x)")
          }
         Function Execution
         if (is.character(x) == TRUE){
           v <- unlist(strsplit(x, ''))
             N <- length(v)
           rev.v <- v
          for (i in 0:(N - 1)){
         rev.v[i + 1] <- v[N - i]
        }
         rev.v <- paste0(rev.v, collapse = '')
            return(rev.v)
         } else {
            x <- as.character(x)
       v <- unlist(strsplit(x, ''))
           rev.v <- v
            N <- length(v)
 for (i in 0:(N - 1)){
   rev.v[i + 1] <- v[N - i]
 }
rev.v <- paste0(rev.v, collapse = '')
rev.v <- as.numeric(rev.v)
  return(rev.v)
   }
 }

    the function vector.reverse() has been deleted to reduce the length of 
    this code

    is.palindrome <- function(x){
  Args:
     x : vector whose elements will be tested for palindromicity, can be of 
 length >= 1
  Returns:
    TRUE : if an element in x or x is palindromic
    FALSE: if an element in x or x is not palindromic

   Function Execution:
  if (is.vector(x) == TRUE & length(x) > 1){
    x.prime <- vector(length = length(x))
    for (i in 1:length(x)){
      x.prime [i] <- reverse(x [i])
 }
   return(x.prime == x)
 } else {
 ifelse(reverse(x) == x, return(TRUE), return(FALSE))
     }
   }

  palindromes between 10000 and 999*999
 Palin <- (100*100):(999*999)
 Palin <- Palin [is.palindrome(Palin) == 1]
 i.s <- vector('numeric', length = length(Palin))
 j.s <- vector('numeric', length = length(Palin))

   Factoring each of the palindromes
   for (i in 100:999){
     for (j in 100:999){
       if (sum(i * j == Palin) == 1){
         i.s[i-99] <- i
         j.s[i-99] <- j

      }
     }
   }
 product <- i.s * j.s
 which(i.s * j.s == max(product)) -> Ans
 paste(i.s[Ans[1]], "and", j.s[Ans[1]], "give the largest two 3-digit 
  palindrome")



ANSWER
  993 * 913 = 906609

ENJOY!

Another simple solution written in C#

private static void Main(string[] args)
        {
            var maxi = 0;
            var maxj = 0;
            var maxProd = 0;
            for (var i = 999; i > 100; i--)
            for (var j = 999; j > 100; j--)
            {
                var product = i * j;
                if (IsPalindrome(product))
                    if (product > maxProd)
                    {
                        maxi = i;
                        maxj = j;
                        maxProd = product;
                    }
            }
            Console.WriteLine(
                "The highest Palindrome number made from the product of two 3-digit numbers is {0}*{1}={2}", maxi, maxj,
                maxProd);
            Console.ReadKey();
        }

        public static bool IsPalindrome(int number)
        {
            var numberString = number.ToString();
            var reverseString = string.Empty;
            for (var i = numberString.Length - 1; i >= 0; --i)
                reverseString += numberString[i];
            return numberString == reverseString;
        }

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);
}

}

Here is the code in c++

#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;
  }

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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!