2

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 two 2-digit numbers is 9009 = 91 × 99. Find the largest palindrome made from the product of two 3-digit numbers.

Here is my solution , it's output is 997799 , however that's not the correct answer ,I wonder where is the problem:

package projecteuler;

public class Pro4 {

    public static void main(String[] args) {

        for(int i=999*999;i>=100*100;i--){
            if(isPalindrome(i)==true){
                System.out.println(i);
                break;
            }
        }
    }

    static boolean isPalindrome(int x){
        int[] bits = new int[7];
        int index=1;
        while(x>0){
            bits[index]=x%10;
            index++;
            x/=10;
        }
        for(int i=1;i<=index/2;i++){
            if(bits[i]!=bits[index-i]){
                return false;
            }
        }
        return true;
    }

}
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
Praveen Kumar
  • 1,624
  • 5
  • 18
  • 21
  • Have you examined it through a debugger? There's a lot that could be going wrong with it, frankly - examining it with a step debugger would be a good first step towards figuring out the issue. – Makoto Jul 16 '14 at 04:24
  • The problem is here : "for(int i=999*999;i>=100*100;i--)". When you run that for loop, you will process many numbers that are not the products two 3-digit numbers. I guess that your output 997799 may not be a product of two 3-digit numbers. Some mathematicians may be able to prove that easily. (Unfortunately, I am not a mathematician). – Job_September_2020 Feb 01 '22 at 08:14

21 Answers21

10

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
ROMANIA_engineer
  • 54,432
  • 29
  • 203
  • 199
  • 3
    +1 for this is best solution so far. I also like the fact that you first compare to max before determining whether it is a palindrome. That inexpensive operation might save some time. However, there is room for optimization. 1) you are calculating almost all products twice, since `i*j=j*i` you only need to calculate the product for all `j>=i`. 2) for small `i` there is no `j < 1000` that will produce a product bigger than `max`. so adding `if ( max / i > 1000) {i=99}` will effectively shorten the time to calculate the max palindrome to 1/10 or less of the current time. – Peter Schuetze Nov 11 '14 at 16:04
  • How can we generalize the lowest max value? As you are initializing max to 100001 for the three digits – mohit uprim Jul 09 '18 at 09:38
  • @mohituprim , I edited the post because that value was wrong. Even if it is a palindrome 100001 cannot be written as 2 3-digit number product. Instead you can use 110011 as a correct starting value. Unfortunately, I don't have a rule that could work for all combinations, so using a negative value / 100*100 is applicable for all situations, even if it's slower. – ROMANIA_engineer Jul 09 '18 at 13:18
  • @ROMANIA_engineer, Can I run and test above code online. Please suggest a website. – pmh Feb 28 '20 at 05:52
  • 1
    @pmh, yes, here are 2 good examples: ideone.com and repl.it/languages/java10 . – ROMANIA_engineer Feb 28 '20 at 21:02
  • Would you please tell me what is the time complexity for this code ? How about space complexity ? – Job_September_2020 Feb 01 '22 at 08:08
3

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.

Sanjeev Kumar
  • 680
  • 8
  • 16
1

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.

Robby Cornelissen
  • 91,784
  • 22
  • 134
  • 156
1

Elrond_EGLDer's excellent solution could be improved with

  • A string-based IsPalindrome() verification
  • Instant production of results for even number digit multipliers
  • Our results should always be divisible by 11 (maybe based on this)
  • Implement for n digits

This is the output it produces:

 3 digits:            913 x            993 =                       906609, 7ms
 4 digits:           9999 x           9901 =                     99000099, 0ms
 5 digits:          99681 x          99979 =                   9966006699, 11ms
 6 digits:         999999 x         999001 =                 999000000999, 0ms
 7 digits:        9997647 x        9998017 =               99956644665999, 812ms
 8 digits:       99999999 x       99990001 =             9999000000009999, 0ms
 9 digits:      999920317 x      999980347 =           999900665566009999, 508259ms
10 digits:     9999999999 x     9999900001 =         99999000000000099999, 0ms
11 digits:    99999943851 x    99999996349 =       9999994020000204999999, 420031ms
12 digits:   999999999999 x   999999000001 =     999999000000000000999999, 0ms
13 digits: ?
14 digits: 99999999999999 x 99999990000001 = 9999999000000000000009999999, 0ms

Here is the C# code: using System.Diagnostics; using System.Numerics;

static bool IsPalindrome(BigInteger palindromCandidate)
{
    string palindromeString = palindromCandidate.ToString();
    int length = palindromeString.Length;

    if (length % 2 != 0)
    {
        return false;
    }

    int i = 0;

    while (i < length / 2)
    {
        if (palindromeString[i] != palindromeString[length - 1 - i])
        {
            return false;
        }

        i++;
    }

    return true;
}

/// <summary>
/// Palindromes with even number of digits in their multipliers always follow a 
/// pattern:
///  6:     999001 x     999999 =         999000000999
///  8:   99990001 x   99999999 =     9999000000009999
/// 10: 9999900001 x 9999999999 = 99999000000000099999
/// </summary>
static BigInteger GeneratePalindromeFromEvenDigits(
    int nrDigits,
    out BigInteger x1,
    out BigInteger x2)
{
    if (nrDigits % 2 != 0)
    {
        x1 = 0;
        x2 = 0;

        return 0;
    }

    // E.g. 9999999999
    x1 = (BigInteger)(Math.Pow(10, nrDigits) - 1);

    // E.g. 9999900001
    x2 = x1 - (BigInteger)Math.Pow(10, nrDigits / 2) + 2;

    return x1 * x2;
}

static BigInteger Palindrome(int nrDigits, out BigInteger x1, out BigInteger x2)
{
    const bool reduceSpace = true;
    x1 = 0;
    x2 = 0;

    // 1 digit numbers cannot form a palindrome
    if (nrDigits <= 1)
    {
        return 0;
    }

    if (nrDigits % 2 == 0)
    {
        // In case of even numbered digits we cen directly construct the results
        return GeneratePalindromeFromEvenDigits(nrDigits, out x1, out x2);
    }

    // 999999
    BigInteger startFromMax = (BigInteger)Math.Pow(10, nrDigits) - 1;

    // 100000
    BigInteger endWithSmallest = (BigInteger)Math.Pow(10, nrDigits - 1);

    if (reduceSpace)
    {
        // Cheat, by artificially reducing the explored space
        // 990000
        endWithSmallest =
            startFromMax -
            (BigInteger)Math.Pow(10, (nrDigits / 2) + 1);
    }

    BigInteger max = 0;


    for (BigInteger i = startFromMax; i >= endWithSmallest; i--)
    {
        if (max >= i * startFromMax)
        {
            break;
        }

        // Since i*j = j * i you only need to calculate the product for all j>= i
        for (BigInteger j = i; j <= startFromMax; j++)
        {
            BigInteger palindrome = i * j;

            if (
                max < palindrome &&
                palindrome % 11 == 0 &&
                IsPalindrome(palindrome))
            {
                x1 = i;
                x2 = j;

                max = palindrome;
            }
        }
    }

    return max;
}

Stopwatch sw = new();

for (int x = 1; x <= 14; x++)
{
    sw.Restart();
    BigInteger max = Palindrome(x, out BigInteger i, out BigInteger j);

    if (max == 0)
    {
        Console.WriteLine($"{x,2} digits: No solution was found, " +
            $"{sw.ElapsedMilliseconds}ms");
    }
    else
    {
        Console.WriteLine($"{x,2} digits: {i,14} × {j,14} = {max,28}, " +
            $"{sw.ElapsedMilliseconds}ms");
    }
}
Germstorm
  • 9,709
  • 14
  • 67
  • 83
0

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.

Peter Schuetze
  • 16,185
  • 4
  • 44
  • 58
Yagnesh Agola
  • 4,556
  • 6
  • 37
  • 50
0

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.

Saif Al Falah
  • 358
  • 5
  • 16
0

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)
SOLID
  • 1
0

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)

Vikas Tawniya
  • 1,323
  • 1
  • 13
  • 22
0

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

}
0

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

}

mturner
  • 21
  • 2
0

JAVASCRIPT
Hey i looked over some of the answers and it was very confusing here is what i got: First i call the function getPalindrome() from a button and i only give it the number of digits. Then with the first for loop i set max to the largest number with the supplied digits by adding 9 * 10^0 (9), 9 * 10^1 (90) etc. Then i have two nested loops that go from the last two numbers down (ex. 99 and 98). The first loop's condition is mostly irrelevant because the largest palindrome will always be in the last numbers (ex between 90 and 99, 990 and 999 etc) . Inside the loop i check if both numbers are not divisible by 11 that means we can't have a palindrome so i just skip it and lower the second number. If one of them is divisible by 11, the check for palindrome function is called. Even though i don't think this solution is better/faster than the others, it is simpler and easier to understand.

const getPalindrome = () => {
let max = 0;
for (let i = 0; i < digit; i++) {
  max += 9 * Math.pow(10, i);
}
let min = (max + 1)/10;
let first = max;
let second = max - 1;

for (let i = first; i > min; i--) {
  for (let j = second; j > min * 9; j--) {
    if(i % 11 !== 0 && j % 11 !== 0) {
      continue;
    } else {
      if(checkForPalindrome(i*j)) {
        return setResult(i*j);
      }
    }
  }
} 


}

  const checkForPalindrome = (num) => {
    let digits = `${num}`;
    for (let i = 0; i < Math.floor(digits.length / 2); i++) {
      if(digits[i] !== digits[digits.length-1-i]) {
        return false;
      } 
    }
    return true;
  }
  • So what was wrong with the code in the question? – Null Mar 10 '21 at 13:25
  • I don't understand the question. I thought that the other replies have more complicated code than what i came up with. So I wanted to share my solution even if it may be slower than the other ones at least it's shorter and easier to understand. –  Mar 12 '21 at 09:05
0

Answer to Largest palindrome product in projecteuler Problem 4

Code in Python 3

def large_palindrome(n):
    upper = 10 ** n - 1
    lower = upper // 10  
    max_need = 0

    for i in range(upper, lower, -1):
        for j in range(i, lower, -1):
            mul_number = i * j
            if mul_number < max_need:
                break
            num = mul_number
            num = int(str(num)[::-1])
            if mul_number == num and mul_number > max_need:
                max_need = mul_number

    return max_need

n = 3
print(large_palindrome(n))

output for n=3 is 906609

Masoud_Sh
  • 31
  • 2
0

Sloppy one for Python 3

''' Largest palindrome made from the product of two 3-digit numbers. '''

store = []
for i in range (100, 1000):
   for j in range (100, 1000):
      multiply = str(i*j)
      if (multiply[0]==multiply[-1] and multiply[1]==multiply[-2] and multiply[2]==multiply[-3]):
         store.append(int(multiply))
store.sort()
print(store[-1])
takin
  • 1
  • 1
    Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Mar 11 '22 at 04:19
0

'''python

numbers=[]
for x in range(100,1000):
for y in range (100,1000):
  pro = str(x*y)
  if pro[0]==pro[-1] and pro[1]==pro[-2] and pro[2]==pro[-3]:
    numbers.append(int(pro))
numbers.sort()
print(numbers[-1])''

I've simply created an empty list. Then looping over 2 variables x&y in the range provided by the problem. Convert x*y to str, to access individual elements.

Then I'll throw in the conditions for a palindrome and voila.

Simple yet effective code.

GodHunter
  • 1
  • 1
-1
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;
}
Shree Krishna
  • 8,474
  • 6
  • 40
  • 68
-1

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

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!

-1

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;
        }
Santhosh
  • 729
  • 7
  • 19
-1

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

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

Rajesh Sinha
  • 47
  • 1
  • 8
-1
#include <bits/stdc++.h>
using namespace std;

int main()
{
    ios_base::sync_with_stdio(false);
    cin.tie(NULL);
    int sm=100,lr=999,ans=0;
    for(int i=sm;i<=lr;i++)       //for every number we traverse and find its 
                                   // product with other number
    {
        for(int j=sm;j<=lr;j++)
        {
            int pro=i*j;                    //find product of number 
            string str=to_string(pro);      //  convert to string 
        string rev = string(str.rbegin(),str.rend());  //reverse it 
            if(str==rev)                              //check it with 
          {                                           //string it is equal or 
                                                     //  with reverse
            ans=max(ans,pro);} //storing only max value if it satisfy the  
                               //condition
        }
    }
    cout<<ans; // ans is 906609 
    return 0;
}
Karmesh Duggar
  • 33
  • 1
  • 12
  • 2
    Code dumps do not make for good answers. You should explain *how* and *why* this solves their problem. I recommend reading, "[How do I write a good answer?"](//stackoverflow.com/help/how-to-answer) – John Conde Feb 17 '21 at 01:15