Calculate the largest palindromic number from the product of two 6-digit numbers (100000 to 999999)Finding the largest palindrome from the product of two n-digit numbersLargest palindrome made from the product of two 3-digit numbersProject Euler #4 in C++: largest palindrome product of two 3-digit numbersProject Euler 4: Largest palindrome productProject Euler #4 - finding the largest palindrome from the product of two n-digit numbersGeneralized Project Euler #4: Largest palindrome from product of two n-digit numbers in PythonProject Euler 4 - Largest palindrome productLargest palindrome made from the product of 3-digit numbersFind largest palindrome from the product of two 3-digit numbersThe Next Palindromic number

Does anyone have a method of differentiating informative comments from commented out code?

Taking my Ph.D. advisor out for dinner after graduation

Diagram with cylinder shapes and rectangles

The Apéry's constant and the Airy function

Was the 45.9°C temperature in France in June 2019 the highest ever recorded in France?

Shipped package arrived - didn't order, possible scam?

3-way switches no longer serving their purpose

Can a USB hub be used to access a drive from two devices?

How did the IEC decide to create kibibytes?

Can one block with a protection from color creature?

My professor has told me he will be the corresponding author. Will it hurt my future career?

How to reclaim personal item I've lent to the office without burning bridges?

Did William Shakespeare hide things in his writings?

In layman's terms, does the Luckstone just give a passive +1 to all d20 rolls and saves except for death saves?

Can you create a free-floating MASYU puzzle?

When do flights get cancelled due to fog?

What was the significance of Spider-Man: Far From Home being an MCU Phase 3 film instead of a Phase 4 film?

What exactly is a "murder hobo"?

E12 LED light bulb flickers when OFF in candelabra

Was it ever illegal to name a pig "Napoleon" in France?

Why did Robert F. Kennedy loathe Lyndon B. Johnson?

Why do Martians have to wear space helmets?

As a supervisor, what feedback would you expect from a PhD who quits?

What do you call a situation where you have choices but no good choice?



Calculate the largest palindromic number from the product of two 6-digit numbers (100000 to 999999)


Finding the largest palindrome from the product of two n-digit numbersLargest palindrome made from the product of two 3-digit numbersProject Euler #4 in C++: largest palindrome product of two 3-digit numbersProject Euler 4: Largest palindrome productProject Euler #4 - finding the largest palindrome from the product of two n-digit numbersGeneralized Project Euler #4: Largest palindrome from product of two n-digit numbers in PythonProject Euler 4 - Largest palindrome productLargest palindrome made from the product of 3-digit numbersFind largest palindrome from the product of two 3-digit numbersThe Next Palindromic number






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;








1












$begingroup$


Are there any efficient ways to solve this problem,
for example using bitwise operator?



 public static boolean isPal(long num) 

String numStr = Long.toString(num);
String rNumStr = "";

boolean result = false;

for (int i = numStr.length() - 1; i >= 0 ; --i)
rNumStr += numStr.charAt(i);

//System.out.println(numStr + "," + rNumStr);
try

if (Long.parseLong(numStr) == Long.parseLong(rNumStr))
result = true;
else
result = false;
catch (NumberFormatException e)
//System.err.println("Unable to format. " + e);

return result;



public static void calcPal(int rangeMin, int rangeMax)

long maxp = 0, maxq = 0, maxP = 0;
for (int p = rangeMax; p > rangeMin; p--)
for (int q = rangeMax; q > rangeMin; q--)

long P = p * q;
if (isPal(P))
if (P > maxP)

maxp = p; maxq = q; maxP = P;


System.out.println(maxp + "*" + maxq + "=" + maxP);


public static void main(String[] args)

calcPal(10, 99);
calcPal(100, 999);
calcPal(9000, 9999);
calcPal(10000, 99999);
calcPal(990000, 999999);



The largest palindrome which can be made from the product of two 2-digit (10 to 99) numbers is 9009 (91 × 99). Write a function to calculate the largest palindromic number from the product of two 6-digit numbers (100000 to 999999).










share|improve this question











$endgroup$











  • $begingroup$
    it is my interview question
    $endgroup$
    – Selman Keskin
    8 hours ago

















1












$begingroup$


Are there any efficient ways to solve this problem,
for example using bitwise operator?



 public static boolean isPal(long num) 

String numStr = Long.toString(num);
String rNumStr = "";

boolean result = false;

for (int i = numStr.length() - 1; i >= 0 ; --i)
rNumStr += numStr.charAt(i);

//System.out.println(numStr + "," + rNumStr);
try

if (Long.parseLong(numStr) == Long.parseLong(rNumStr))
result = true;
else
result = false;
catch (NumberFormatException e)
//System.err.println("Unable to format. " + e);

return result;



public static void calcPal(int rangeMin, int rangeMax)

long maxp = 0, maxq = 0, maxP = 0;
for (int p = rangeMax; p > rangeMin; p--)
for (int q = rangeMax; q > rangeMin; q--)

long P = p * q;
if (isPal(P))
if (P > maxP)

maxp = p; maxq = q; maxP = P;


System.out.println(maxp + "*" + maxq + "=" + maxP);


public static void main(String[] args)

calcPal(10, 99);
calcPal(100, 999);
calcPal(9000, 9999);
calcPal(10000, 99999);
calcPal(990000, 999999);



The largest palindrome which can be made from the product of two 2-digit (10 to 99) numbers is 9009 (91 × 99). Write a function to calculate the largest palindromic number from the product of two 6-digit numbers (100000 to 999999).










share|improve this question











$endgroup$











  • $begingroup$
    it is my interview question
    $endgroup$
    – Selman Keskin
    8 hours ago













1












1








1





$begingroup$


Are there any efficient ways to solve this problem,
for example using bitwise operator?



 public static boolean isPal(long num) 

String numStr = Long.toString(num);
String rNumStr = "";

boolean result = false;

for (int i = numStr.length() - 1; i >= 0 ; --i)
rNumStr += numStr.charAt(i);

//System.out.println(numStr + "," + rNumStr);
try

if (Long.parseLong(numStr) == Long.parseLong(rNumStr))
result = true;
else
result = false;
catch (NumberFormatException e)
//System.err.println("Unable to format. " + e);

return result;



public static void calcPal(int rangeMin, int rangeMax)

long maxp = 0, maxq = 0, maxP = 0;
for (int p = rangeMax; p > rangeMin; p--)
for (int q = rangeMax; q > rangeMin; q--)

long P = p * q;
if (isPal(P))
if (P > maxP)

maxp = p; maxq = q; maxP = P;


System.out.println(maxp + "*" + maxq + "=" + maxP);


public static void main(String[] args)

calcPal(10, 99);
calcPal(100, 999);
calcPal(9000, 9999);
calcPal(10000, 99999);
calcPal(990000, 999999);



The largest palindrome which can be made from the product of two 2-digit (10 to 99) numbers is 9009 (91 × 99). Write a function to calculate the largest palindromic number from the product of two 6-digit numbers (100000 to 999999).










share|improve this question











$endgroup$




Are there any efficient ways to solve this problem,
for example using bitwise operator?



 public static boolean isPal(long num) 

String numStr = Long.toString(num);
String rNumStr = "";

boolean result = false;

for (int i = numStr.length() - 1; i >= 0 ; --i)
rNumStr += numStr.charAt(i);

//System.out.println(numStr + "," + rNumStr);
try

if (Long.parseLong(numStr) == Long.parseLong(rNumStr))
result = true;
else
result = false;
catch (NumberFormatException e)
//System.err.println("Unable to format. " + e);

return result;



public static void calcPal(int rangeMin, int rangeMax)

long maxp = 0, maxq = 0, maxP = 0;
for (int p = rangeMax; p > rangeMin; p--)
for (int q = rangeMax; q > rangeMin; q--)

long P = p * q;
if (isPal(P))
if (P > maxP)

maxp = p; maxq = q; maxP = P;


System.out.println(maxp + "*" + maxq + "=" + maxP);


public static void main(String[] args)

calcPal(10, 99);
calcPal(100, 999);
calcPal(9000, 9999);
calcPal(10000, 99999);
calcPal(990000, 999999);



The largest palindrome which can be made from the product of two 2-digit (10 to 99) numbers is 9009 (91 × 99). Write a function to calculate the largest palindromic number from the product of two 6-digit numbers (100000 to 999999).







java programming-challenge interview-questions palindrome






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited 3 hours ago









200_success

134k21 gold badges171 silver badges440 bronze badges




134k21 gold badges171 silver badges440 bronze badges










asked 8 hours ago









Selman KeskinSelman Keskin

162 bronze badges




162 bronze badges











  • $begingroup$
    it is my interview question
    $endgroup$
    – Selman Keskin
    8 hours ago
















  • $begingroup$
    it is my interview question
    $endgroup$
    – Selman Keskin
    8 hours ago















$begingroup$
it is my interview question
$endgroup$
– Selman Keskin
8 hours ago




$begingroup$
it is my interview question
$endgroup$
– Selman Keskin
8 hours ago










2 Answers
2






active

oldest

votes


















2












$begingroup$

In an interview setting it is quite hard to come with an efficient solution (unless you happen to be very good in mental multiplication; however a $99 * 91$ example is a strong hint). The key to an efficient solution is an observation that



$999999 * 999001 = 999000000999$



is a quite large palindromic product. It means that you don't have to test the entire 6-digit ranges of multiplicands. It is enough to test multiplicands only in $[999001.. 999999]$ range. Just $10^6$ candidate pairs rather than $10^12$.



BTW, a similar identity holds for products of longer numbers as well.



Next, you may notice that there are just one thousand palindromic numbers larger than $999000000999$ (they are in form of 999abccba999), and to qualify as a solution is must have a 6-digit factor larger than $999001$. This implies the following algorithm (in pseudocode):



base = 999000000999
abc = 999
while abc >= 0
cba = reverse_digits(abc)
number = base + abc * 1000000 + cba * 1000
for factor in 999001 to sqrt(number)
if number % factor == 0:
return number
abc -= 1


The reverse_digits of a 3-digit number could be done extremely fast (a lookup table, for example). Still a $10^6$ or so rounds, but no expensive tests for palindromicity.



All that said, since the problem stems from Project Euler #4 it is possible that it admits a more elegant number-theoretical solution.






share|improve this answer











$endgroup$




















    2












    $begingroup$

    Bug



     for (int p = rangeMax; p > rangeMin; p--)
    for (int q = rangeMax; q > rangeMin; q--)


    You are not including rangeMin in either of the loops, so you will never test products which involve the lower limit. You want >= in the loop condition:



     for (int p = rangeMax; p >= rangeMin; p--)
    for (int q = rangeMax; q >= rangeMin; q--)


    Commutivity



    Note that p * q == q * p, so you don't need to test all combinations in the range:



     for (int p = rangeMax; p > rangeMin; p--)
    for (int q = rangeMax; q > rangeMin; q--)


    Only the ones where either p >= q or q >= p, which will reduce your search space by close to 50%! For example, you could change the q range to start at the current p value and go down from there:



     for (int p = rangeMax; p >= rangeMin; p--)
    for (int q = p; q >= rangeMin; q--)


    Test order: Fastest tests first!



    isPal(P) is an involved function which will take a bit of time. In comparison, P > maxP is blazingly fast. So instead of:



     if (isPal(P))
    if (P > maxP)

    maxp = p; maxq = q; maxP = P;



    how about:



     if (P > maxP)
    if (isPal(P))

    maxp = p; maxq = q; maxP = P;



    Early termination



    If p*q is ever less than maxP, then multiplying p by any smaller value of q is a waste of time; you can break out of the inner loop, and try the next value of p.



    If p*p is ever less than maxP, and the inner loop only multiplies p by q values which a not greater than p, then you can break out of the outer loop, too!



    String Manipulation



    The following is inefficient, because temporary objects are being created and destroyed during each iteration.



     for (int i = numStr.length() - 1; i >= 0 ; --i)
    rNumStr += numStr.charAt(i);


    It is much better to use a StringBuilder to build up strings character by character, because the StringBuilder maintains a mutable buffer for the interm results.



    Even better, it includes the .reverse() method, which does what you need in one function call.



    StringBuilder sb = new StringBuilder(numStr);
    String rNumStr = sb.reverse().toString();


    Unnecessary Operations



    Why convert numStr to a number using Long.parseLong(numStr)? Isn't the result simply num, the value that was passed in to the function?



    Why convert rNumStr to a number? If num is a palindrome, then aren't numStr and rNumStr equal?



    public static boolean isPal(long num) 

    String numStr = Long.toString(num);
    StringBuilder sb = new StringBuilder(numStr);
    String rNumStr = sb.reverse().toString();

    return numStr.equals(rNumStr);






    share|improve this answer











    $endgroup$












    • $begingroup$
      By associativity you surely meant commutativity.
      $endgroup$
      – vnp
      5 hours ago










    • $begingroup$
      Very minor nitpick: "Fastest tests first" is a reasonable heuristic but even from a speed perspective is not the only axis worth considering. "Most selective test first" is also a reasonable heuristic, and the interplay between test speed and selectivity is intricate. I suspect without measurement that you're right in this case that the quicker test is a good filter, but perhaps it wants fleshing out why.
      $endgroup$
      – Josiah
      5 hours ago






    • 2




      $begingroup$
      In this particular case, as mentioned "you could change the q range to start at the current p value and go down from there." You could do one better than that, and start q at maxP / p if larger. That could allow the P > maxP test to be removed altogether.
      $endgroup$
      – Josiah
      5 hours ago










    • $begingroup$
      @vnp Yup - good catch.
      $endgroup$
      – AJNeufeld
      3 hours ago













    Your Answer






    StackExchange.ifUsing("editor", function ()
    StackExchange.using("externalEditor", function ()
    StackExchange.using("snippets", function ()
    StackExchange.snippets.init();
    );
    );
    , "code-snippets");

    StackExchange.ready(function()
    var channelOptions =
    tags: "".split(" "),
    id: "196"
    ;
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function()
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled)
    StackExchange.using("snippets", function()
    createEditor();
    );

    else
    createEditor();

    );

    function createEditor()
    StackExchange.prepareEditor(
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: false,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: null,
    bindNavPrevention: true,
    postfix: "",
    imageUploader:
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    ,
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    );



    );













    draft saved

    draft discarded


















    StackExchange.ready(
    function ()
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f223582%2fcalculate-the-largest-palindromic-number-from-the-product-of-two-6-digit-numbers%23new-answer', 'question_page');

    );

    Post as a guest















    Required, but never shown

























    2 Answers
    2






    active

    oldest

    votes








    2 Answers
    2






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    2












    $begingroup$

    In an interview setting it is quite hard to come with an efficient solution (unless you happen to be very good in mental multiplication; however a $99 * 91$ example is a strong hint). The key to an efficient solution is an observation that



    $999999 * 999001 = 999000000999$



    is a quite large palindromic product. It means that you don't have to test the entire 6-digit ranges of multiplicands. It is enough to test multiplicands only in $[999001.. 999999]$ range. Just $10^6$ candidate pairs rather than $10^12$.



    BTW, a similar identity holds for products of longer numbers as well.



    Next, you may notice that there are just one thousand palindromic numbers larger than $999000000999$ (they are in form of 999abccba999), and to qualify as a solution is must have a 6-digit factor larger than $999001$. This implies the following algorithm (in pseudocode):



    base = 999000000999
    abc = 999
    while abc >= 0
    cba = reverse_digits(abc)
    number = base + abc * 1000000 + cba * 1000
    for factor in 999001 to sqrt(number)
    if number % factor == 0:
    return number
    abc -= 1


    The reverse_digits of a 3-digit number could be done extremely fast (a lookup table, for example). Still a $10^6$ or so rounds, but no expensive tests for palindromicity.



    All that said, since the problem stems from Project Euler #4 it is possible that it admits a more elegant number-theoretical solution.






    share|improve this answer











    $endgroup$

















      2












      $begingroup$

      In an interview setting it is quite hard to come with an efficient solution (unless you happen to be very good in mental multiplication; however a $99 * 91$ example is a strong hint). The key to an efficient solution is an observation that



      $999999 * 999001 = 999000000999$



      is a quite large palindromic product. It means that you don't have to test the entire 6-digit ranges of multiplicands. It is enough to test multiplicands only in $[999001.. 999999]$ range. Just $10^6$ candidate pairs rather than $10^12$.



      BTW, a similar identity holds for products of longer numbers as well.



      Next, you may notice that there are just one thousand palindromic numbers larger than $999000000999$ (they are in form of 999abccba999), and to qualify as a solution is must have a 6-digit factor larger than $999001$. This implies the following algorithm (in pseudocode):



      base = 999000000999
      abc = 999
      while abc >= 0
      cba = reverse_digits(abc)
      number = base + abc * 1000000 + cba * 1000
      for factor in 999001 to sqrt(number)
      if number % factor == 0:
      return number
      abc -= 1


      The reverse_digits of a 3-digit number could be done extremely fast (a lookup table, for example). Still a $10^6$ or so rounds, but no expensive tests for palindromicity.



      All that said, since the problem stems from Project Euler #4 it is possible that it admits a more elegant number-theoretical solution.






      share|improve this answer











      $endgroup$















        2












        2








        2





        $begingroup$

        In an interview setting it is quite hard to come with an efficient solution (unless you happen to be very good in mental multiplication; however a $99 * 91$ example is a strong hint). The key to an efficient solution is an observation that



        $999999 * 999001 = 999000000999$



        is a quite large palindromic product. It means that you don't have to test the entire 6-digit ranges of multiplicands. It is enough to test multiplicands only in $[999001.. 999999]$ range. Just $10^6$ candidate pairs rather than $10^12$.



        BTW, a similar identity holds for products of longer numbers as well.



        Next, you may notice that there are just one thousand palindromic numbers larger than $999000000999$ (they are in form of 999abccba999), and to qualify as a solution is must have a 6-digit factor larger than $999001$. This implies the following algorithm (in pseudocode):



        base = 999000000999
        abc = 999
        while abc >= 0
        cba = reverse_digits(abc)
        number = base + abc * 1000000 + cba * 1000
        for factor in 999001 to sqrt(number)
        if number % factor == 0:
        return number
        abc -= 1


        The reverse_digits of a 3-digit number could be done extremely fast (a lookup table, for example). Still a $10^6$ or so rounds, but no expensive tests for palindromicity.



        All that said, since the problem stems from Project Euler #4 it is possible that it admits a more elegant number-theoretical solution.






        share|improve this answer











        $endgroup$



        In an interview setting it is quite hard to come with an efficient solution (unless you happen to be very good in mental multiplication; however a $99 * 91$ example is a strong hint). The key to an efficient solution is an observation that



        $999999 * 999001 = 999000000999$



        is a quite large palindromic product. It means that you don't have to test the entire 6-digit ranges of multiplicands. It is enough to test multiplicands only in $[999001.. 999999]$ range. Just $10^6$ candidate pairs rather than $10^12$.



        BTW, a similar identity holds for products of longer numbers as well.



        Next, you may notice that there are just one thousand palindromic numbers larger than $999000000999$ (they are in form of 999abccba999), and to qualify as a solution is must have a 6-digit factor larger than $999001$. This implies the following algorithm (in pseudocode):



        base = 999000000999
        abc = 999
        while abc >= 0
        cba = reverse_digits(abc)
        number = base + abc * 1000000 + cba * 1000
        for factor in 999001 to sqrt(number)
        if number % factor == 0:
        return number
        abc -= 1


        The reverse_digits of a 3-digit number could be done extremely fast (a lookup table, for example). Still a $10^6$ or so rounds, but no expensive tests for palindromicity.



        All that said, since the problem stems from Project Euler #4 it is possible that it admits a more elegant number-theoretical solution.







        share|improve this answer














        share|improve this answer



        share|improve this answer








        edited 4 hours ago

























        answered 4 hours ago









        vnpvnp

        42.3k2 gold badges35 silver badges109 bronze badges




        42.3k2 gold badges35 silver badges109 bronze badges























            2












            $begingroup$

            Bug



             for (int p = rangeMax; p > rangeMin; p--)
            for (int q = rangeMax; q > rangeMin; q--)


            You are not including rangeMin in either of the loops, so you will never test products which involve the lower limit. You want >= in the loop condition:



             for (int p = rangeMax; p >= rangeMin; p--)
            for (int q = rangeMax; q >= rangeMin; q--)


            Commutivity



            Note that p * q == q * p, so you don't need to test all combinations in the range:



             for (int p = rangeMax; p > rangeMin; p--)
            for (int q = rangeMax; q > rangeMin; q--)


            Only the ones where either p >= q or q >= p, which will reduce your search space by close to 50%! For example, you could change the q range to start at the current p value and go down from there:



             for (int p = rangeMax; p >= rangeMin; p--)
            for (int q = p; q >= rangeMin; q--)


            Test order: Fastest tests first!



            isPal(P) is an involved function which will take a bit of time. In comparison, P > maxP is blazingly fast. So instead of:



             if (isPal(P))
            if (P > maxP)

            maxp = p; maxq = q; maxP = P;



            how about:



             if (P > maxP)
            if (isPal(P))

            maxp = p; maxq = q; maxP = P;



            Early termination



            If p*q is ever less than maxP, then multiplying p by any smaller value of q is a waste of time; you can break out of the inner loop, and try the next value of p.



            If p*p is ever less than maxP, and the inner loop only multiplies p by q values which a not greater than p, then you can break out of the outer loop, too!



            String Manipulation



            The following is inefficient, because temporary objects are being created and destroyed during each iteration.



             for (int i = numStr.length() - 1; i >= 0 ; --i)
            rNumStr += numStr.charAt(i);


            It is much better to use a StringBuilder to build up strings character by character, because the StringBuilder maintains a mutable buffer for the interm results.



            Even better, it includes the .reverse() method, which does what you need in one function call.



            StringBuilder sb = new StringBuilder(numStr);
            String rNumStr = sb.reverse().toString();


            Unnecessary Operations



            Why convert numStr to a number using Long.parseLong(numStr)? Isn't the result simply num, the value that was passed in to the function?



            Why convert rNumStr to a number? If num is a palindrome, then aren't numStr and rNumStr equal?



            public static boolean isPal(long num) 

            String numStr = Long.toString(num);
            StringBuilder sb = new StringBuilder(numStr);
            String rNumStr = sb.reverse().toString();

            return numStr.equals(rNumStr);






            share|improve this answer











            $endgroup$












            • $begingroup$
              By associativity you surely meant commutativity.
              $endgroup$
              – vnp
              5 hours ago










            • $begingroup$
              Very minor nitpick: "Fastest tests first" is a reasonable heuristic but even from a speed perspective is not the only axis worth considering. "Most selective test first" is also a reasonable heuristic, and the interplay between test speed and selectivity is intricate. I suspect without measurement that you're right in this case that the quicker test is a good filter, but perhaps it wants fleshing out why.
              $endgroup$
              – Josiah
              5 hours ago






            • 2




              $begingroup$
              In this particular case, as mentioned "you could change the q range to start at the current p value and go down from there." You could do one better than that, and start q at maxP / p if larger. That could allow the P > maxP test to be removed altogether.
              $endgroup$
              – Josiah
              5 hours ago










            • $begingroup$
              @vnp Yup - good catch.
              $endgroup$
              – AJNeufeld
              3 hours ago















            2












            $begingroup$

            Bug



             for (int p = rangeMax; p > rangeMin; p--)
            for (int q = rangeMax; q > rangeMin; q--)


            You are not including rangeMin in either of the loops, so you will never test products which involve the lower limit. You want >= in the loop condition:



             for (int p = rangeMax; p >= rangeMin; p--)
            for (int q = rangeMax; q >= rangeMin; q--)


            Commutivity



            Note that p * q == q * p, so you don't need to test all combinations in the range:



             for (int p = rangeMax; p > rangeMin; p--)
            for (int q = rangeMax; q > rangeMin; q--)


            Only the ones where either p >= q or q >= p, which will reduce your search space by close to 50%! For example, you could change the q range to start at the current p value and go down from there:



             for (int p = rangeMax; p >= rangeMin; p--)
            for (int q = p; q >= rangeMin; q--)


            Test order: Fastest tests first!



            isPal(P) is an involved function which will take a bit of time. In comparison, P > maxP is blazingly fast. So instead of:



             if (isPal(P))
            if (P > maxP)

            maxp = p; maxq = q; maxP = P;



            how about:



             if (P > maxP)
            if (isPal(P))

            maxp = p; maxq = q; maxP = P;



            Early termination



            If p*q is ever less than maxP, then multiplying p by any smaller value of q is a waste of time; you can break out of the inner loop, and try the next value of p.



            If p*p is ever less than maxP, and the inner loop only multiplies p by q values which a not greater than p, then you can break out of the outer loop, too!



            String Manipulation



            The following is inefficient, because temporary objects are being created and destroyed during each iteration.



             for (int i = numStr.length() - 1; i >= 0 ; --i)
            rNumStr += numStr.charAt(i);


            It is much better to use a StringBuilder to build up strings character by character, because the StringBuilder maintains a mutable buffer for the interm results.



            Even better, it includes the .reverse() method, which does what you need in one function call.



            StringBuilder sb = new StringBuilder(numStr);
            String rNumStr = sb.reverse().toString();


            Unnecessary Operations



            Why convert numStr to a number using Long.parseLong(numStr)? Isn't the result simply num, the value that was passed in to the function?



            Why convert rNumStr to a number? If num is a palindrome, then aren't numStr and rNumStr equal?



            public static boolean isPal(long num) 

            String numStr = Long.toString(num);
            StringBuilder sb = new StringBuilder(numStr);
            String rNumStr = sb.reverse().toString();

            return numStr.equals(rNumStr);






            share|improve this answer











            $endgroup$












            • $begingroup$
              By associativity you surely meant commutativity.
              $endgroup$
              – vnp
              5 hours ago










            • $begingroup$
              Very minor nitpick: "Fastest tests first" is a reasonable heuristic but even from a speed perspective is not the only axis worth considering. "Most selective test first" is also a reasonable heuristic, and the interplay between test speed and selectivity is intricate. I suspect without measurement that you're right in this case that the quicker test is a good filter, but perhaps it wants fleshing out why.
              $endgroup$
              – Josiah
              5 hours ago






            • 2




              $begingroup$
              In this particular case, as mentioned "you could change the q range to start at the current p value and go down from there." You could do one better than that, and start q at maxP / p if larger. That could allow the P > maxP test to be removed altogether.
              $endgroup$
              – Josiah
              5 hours ago










            • $begingroup$
              @vnp Yup - good catch.
              $endgroup$
              – AJNeufeld
              3 hours ago













            2












            2








            2





            $begingroup$

            Bug



             for (int p = rangeMax; p > rangeMin; p--)
            for (int q = rangeMax; q > rangeMin; q--)


            You are not including rangeMin in either of the loops, so you will never test products which involve the lower limit. You want >= in the loop condition:



             for (int p = rangeMax; p >= rangeMin; p--)
            for (int q = rangeMax; q >= rangeMin; q--)


            Commutivity



            Note that p * q == q * p, so you don't need to test all combinations in the range:



             for (int p = rangeMax; p > rangeMin; p--)
            for (int q = rangeMax; q > rangeMin; q--)


            Only the ones where either p >= q or q >= p, which will reduce your search space by close to 50%! For example, you could change the q range to start at the current p value and go down from there:



             for (int p = rangeMax; p >= rangeMin; p--)
            for (int q = p; q >= rangeMin; q--)


            Test order: Fastest tests first!



            isPal(P) is an involved function which will take a bit of time. In comparison, P > maxP is blazingly fast. So instead of:



             if (isPal(P))
            if (P > maxP)

            maxp = p; maxq = q; maxP = P;



            how about:



             if (P > maxP)
            if (isPal(P))

            maxp = p; maxq = q; maxP = P;



            Early termination



            If p*q is ever less than maxP, then multiplying p by any smaller value of q is a waste of time; you can break out of the inner loop, and try the next value of p.



            If p*p is ever less than maxP, and the inner loop only multiplies p by q values which a not greater than p, then you can break out of the outer loop, too!



            String Manipulation



            The following is inefficient, because temporary objects are being created and destroyed during each iteration.



             for (int i = numStr.length() - 1; i >= 0 ; --i)
            rNumStr += numStr.charAt(i);


            It is much better to use a StringBuilder to build up strings character by character, because the StringBuilder maintains a mutable buffer for the interm results.



            Even better, it includes the .reverse() method, which does what you need in one function call.



            StringBuilder sb = new StringBuilder(numStr);
            String rNumStr = sb.reverse().toString();


            Unnecessary Operations



            Why convert numStr to a number using Long.parseLong(numStr)? Isn't the result simply num, the value that was passed in to the function?



            Why convert rNumStr to a number? If num is a palindrome, then aren't numStr and rNumStr equal?



            public static boolean isPal(long num) 

            String numStr = Long.toString(num);
            StringBuilder sb = new StringBuilder(numStr);
            String rNumStr = sb.reverse().toString();

            return numStr.equals(rNumStr);






            share|improve this answer











            $endgroup$



            Bug



             for (int p = rangeMax; p > rangeMin; p--)
            for (int q = rangeMax; q > rangeMin; q--)


            You are not including rangeMin in either of the loops, so you will never test products which involve the lower limit. You want >= in the loop condition:



             for (int p = rangeMax; p >= rangeMin; p--)
            for (int q = rangeMax; q >= rangeMin; q--)


            Commutivity



            Note that p * q == q * p, so you don't need to test all combinations in the range:



             for (int p = rangeMax; p > rangeMin; p--)
            for (int q = rangeMax; q > rangeMin; q--)


            Only the ones where either p >= q or q >= p, which will reduce your search space by close to 50%! For example, you could change the q range to start at the current p value and go down from there:



             for (int p = rangeMax; p >= rangeMin; p--)
            for (int q = p; q >= rangeMin; q--)


            Test order: Fastest tests first!



            isPal(P) is an involved function which will take a bit of time. In comparison, P > maxP is blazingly fast. So instead of:



             if (isPal(P))
            if (P > maxP)

            maxp = p; maxq = q; maxP = P;



            how about:



             if (P > maxP)
            if (isPal(P))

            maxp = p; maxq = q; maxP = P;



            Early termination



            If p*q is ever less than maxP, then multiplying p by any smaller value of q is a waste of time; you can break out of the inner loop, and try the next value of p.



            If p*p is ever less than maxP, and the inner loop only multiplies p by q values which a not greater than p, then you can break out of the outer loop, too!



            String Manipulation



            The following is inefficient, because temporary objects are being created and destroyed during each iteration.



             for (int i = numStr.length() - 1; i >= 0 ; --i)
            rNumStr += numStr.charAt(i);


            It is much better to use a StringBuilder to build up strings character by character, because the StringBuilder maintains a mutable buffer for the interm results.



            Even better, it includes the .reverse() method, which does what you need in one function call.



            StringBuilder sb = new StringBuilder(numStr);
            String rNumStr = sb.reverse().toString();


            Unnecessary Operations



            Why convert numStr to a number using Long.parseLong(numStr)? Isn't the result simply num, the value that was passed in to the function?



            Why convert rNumStr to a number? If num is a palindrome, then aren't numStr and rNumStr equal?



            public static boolean isPal(long num) 

            String numStr = Long.toString(num);
            StringBuilder sb = new StringBuilder(numStr);
            String rNumStr = sb.reverse().toString();

            return numStr.equals(rNumStr);







            share|improve this answer














            share|improve this answer



            share|improve this answer








            edited 3 hours ago

























            answered 6 hours ago









            AJNeufeldAJNeufeld

            9,5231 gold badge8 silver badges32 bronze badges




            9,5231 gold badge8 silver badges32 bronze badges











            • $begingroup$
              By associativity you surely meant commutativity.
              $endgroup$
              – vnp
              5 hours ago










            • $begingroup$
              Very minor nitpick: "Fastest tests first" is a reasonable heuristic but even from a speed perspective is not the only axis worth considering. "Most selective test first" is also a reasonable heuristic, and the interplay between test speed and selectivity is intricate. I suspect without measurement that you're right in this case that the quicker test is a good filter, but perhaps it wants fleshing out why.
              $endgroup$
              – Josiah
              5 hours ago






            • 2




              $begingroup$
              In this particular case, as mentioned "you could change the q range to start at the current p value and go down from there." You could do one better than that, and start q at maxP / p if larger. That could allow the P > maxP test to be removed altogether.
              $endgroup$
              – Josiah
              5 hours ago










            • $begingroup$
              @vnp Yup - good catch.
              $endgroup$
              – AJNeufeld
              3 hours ago
















            • $begingroup$
              By associativity you surely meant commutativity.
              $endgroup$
              – vnp
              5 hours ago










            • $begingroup$
              Very minor nitpick: "Fastest tests first" is a reasonable heuristic but even from a speed perspective is not the only axis worth considering. "Most selective test first" is also a reasonable heuristic, and the interplay between test speed and selectivity is intricate. I suspect without measurement that you're right in this case that the quicker test is a good filter, but perhaps it wants fleshing out why.
              $endgroup$
              – Josiah
              5 hours ago






            • 2




              $begingroup$
              In this particular case, as mentioned "you could change the q range to start at the current p value and go down from there." You could do one better than that, and start q at maxP / p if larger. That could allow the P > maxP test to be removed altogether.
              $endgroup$
              – Josiah
              5 hours ago










            • $begingroup$
              @vnp Yup - good catch.
              $endgroup$
              – AJNeufeld
              3 hours ago















            $begingroup$
            By associativity you surely meant commutativity.
            $endgroup$
            – vnp
            5 hours ago




            $begingroup$
            By associativity you surely meant commutativity.
            $endgroup$
            – vnp
            5 hours ago












            $begingroup$
            Very minor nitpick: "Fastest tests first" is a reasonable heuristic but even from a speed perspective is not the only axis worth considering. "Most selective test first" is also a reasonable heuristic, and the interplay between test speed and selectivity is intricate. I suspect without measurement that you're right in this case that the quicker test is a good filter, but perhaps it wants fleshing out why.
            $endgroup$
            – Josiah
            5 hours ago




            $begingroup$
            Very minor nitpick: "Fastest tests first" is a reasonable heuristic but even from a speed perspective is not the only axis worth considering. "Most selective test first" is also a reasonable heuristic, and the interplay between test speed and selectivity is intricate. I suspect without measurement that you're right in this case that the quicker test is a good filter, but perhaps it wants fleshing out why.
            $endgroup$
            – Josiah
            5 hours ago




            2




            2




            $begingroup$
            In this particular case, as mentioned "you could change the q range to start at the current p value and go down from there." You could do one better than that, and start q at maxP / p if larger. That could allow the P > maxP test to be removed altogether.
            $endgroup$
            – Josiah
            5 hours ago




            $begingroup$
            In this particular case, as mentioned "you could change the q range to start at the current p value and go down from there." You could do one better than that, and start q at maxP / p if larger. That could allow the P > maxP test to be removed altogether.
            $endgroup$
            – Josiah
            5 hours ago












            $begingroup$
            @vnp Yup - good catch.
            $endgroup$
            – AJNeufeld
            3 hours ago




            $begingroup$
            @vnp Yup - good catch.
            $endgroup$
            – AJNeufeld
            3 hours ago

















            draft saved

            draft discarded
















































            Thanks for contributing an answer to Code Review Stack Exchange!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid


            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.

            Use MathJax to format equations. MathJax reference.


            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function ()
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f223582%2fcalculate-the-largest-palindromic-number-from-the-product-of-two-6-digit-numbers%23new-answer', 'question_page');

            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            Invision Community Contents History See also References External links Navigation menuProprietaryinvisioncommunity.comIPS Community ForumsIPS Community Forumsthis blog entry"License Changes, IP.Board 3.4, and the Future""Interview -- Matt Mecham of Ibforums""CEO Invision Power Board, Matt Mecham Is a Liar, Thief!"IPB License Explanation 1.3, 1.3.1, 2.0, and 2.1ArchivedSecurity Fixes, Updates And Enhancements For IPB 1.3.1Archived"New Demo Accounts - Invision Power Services"the original"New Default Skin"the original"Invision Power Board 3.0.0 and Applications Released"the original"Archived copy"the original"Perpetual licenses being done away with""Release Notes - Invision Power Services""Introducing: IPS Community Suite 4!"Invision Community Release Notes

            Canceling a color specificationRandomly assigning color to Graphics3D objects?Default color for Filling in Mathematica 9Coloring specific elements of sets with a prime modified order in an array plotHow to pick a color differing significantly from the colors already in a given color list?Detection of the text colorColor numbers based on their valueCan color schemes for use with ColorData include opacity specification?My dynamic color schemes

            Tom Holland Mục lục Đầu đời và giáo dục | Sự nghiệp | Cuộc sống cá nhân | Phim tham gia | Giải thưởng và đề cử | Chú thích | Liên kết ngoài | Trình đơn chuyển hướngProfile“Person Details for Thomas Stanley Holland, "England and Wales Birth Registration Index, 1837-2008" — FamilySearch.org”"Meet Tom Holland... the 16-year-old star of The Impossible""Schoolboy actor Tom Holland finds himself in Oscar contention for role in tsunami drama"“Naomi Watts on the Prince William and Harry's reaction to her film about the late Princess Diana”lưu trữ"Holland and Pflueger Are West End's Two New 'Billy Elliots'""I'm so envious of my son, the movie star! British writer Dominic Holland's spent 20 years trying to crack Hollywood - but he's been beaten to it by a very unlikely rival"“Richard and Margaret Povey of Jersey, Channel Islands, UK: Information about Thomas Stanley Holland”"Tom Holland to play Billy Elliot""New Billy Elliot leaving the garage"Billy Elliot the Musical - Tom Holland - Billy"A Tale of four Billys: Tom Holland""The Feel Good Factor""Thames Christian College schoolboys join Myleene Klass for The Feelgood Factor""Government launches £600,000 arts bursaries pilot""BILLY's Chapman, Holland, Gardner & Jackson-Keen Visit Prime Minister""Elton John 'blown away' by Billy Elliot fifth birthday" (video with John's interview and fragments of Holland's performance)"First News interviews Arrietty's Tom Holland"“33rd Critics' Circle Film Awards winners”“National Board of Review Current Awards”Bản gốc"Ron Howard Whaling Tale 'In The Heart Of The Sea' Casts Tom Holland"“'Spider-Man' Finds Tom Holland to Star as New Web-Slinger”lưu trữ“Captain America: Civil War (2016)”“Film Review: ‘Captain America: Civil War’”lưu trữ“‘Captain America: Civil War’ review: Choose your own avenger”lưu trữ“The Lost City of Z reviews”“Sony Pictures and Marvel Studios Find Their 'Spider-Man' Star and Director”“‘Mary Magdalene’, ‘Current War’ & ‘Wind River’ Get 2017 Release Dates From Weinstein”“Lionsgate Unleashing Daisy Ridley & Tom Holland Starrer ‘Chaos Walking’ In Cannes”“PTA's 'Master' Leads Chicago Film Critics Nominations, UPDATED: Houston and Indiana Critics Nominations”“Nominaciones Goya 2013 Telecinco Cinema – ENG”“Jameson Empire Film Awards: Martin Freeman wins best actor for performance in The Hobbit”“34th Annual Young Artist Awards”Bản gốc“Teen Choice Awards 2016—Captain America: Civil War Leads Second Wave of Nominations”“BAFTA Film Award Nominations: ‘La La Land’ Leads Race”“Saturn Awards Nominations 2017: 'Rogue One,' 'Walking Dead' Lead”Tom HollandTom HollandTom HollandTom Hollandmedia.gettyimages.comWorldCat Identities300279794no20130442900000 0004 0355 42791085670554170004732cb16706349t(data)XX5557367