Calculate the largest palindromic number from the product of two 6-digit numbers (100000 to 999999)Finding...
Why do Martians have to wear space helmets?
Examples of fluid (including air) being used to transmit digital data?
Is this car delivery via Ebay Motors on Craigslist a scam?
Did William Shakespeare hide things in his writings?
I don't want to be introduced as a "Minority Novelist"
Where are the Wazirs?
How can I use my cell phone's light as a reading light?
What are the consequences for a developed nation to not accept any refugee?
Was it ever illegal to name a pig "Napoleon" in France?
Four ships at the ocean with the same distance
How should I ask for a "pint" in countries that use metric?
How do I talk to my wife about unrealistic expectations?
What was the significance of Spider-Man: Far From Home being an MCU Phase 3 film instead of a Phase 4 film?
QR codes, do people use them?
Why do people prefer metropolitan areas, considering monsters and villains?
Can one block with a protection from color creature?
How to evaluate the performance of open source solver?
Computer name naming convention for security
Jimmy needs your help!
How do resistors generate different heat if we make the current fixed and changed the voltage and resistance? Notice the flow of charge is constant
Tesco's Burger Relish Best Before End date number
How to understand flavors and when to use combination of them?
When is one 'Ready' to make Original Contributions to Mathematics?
Which is a better conductor, a very thick rubber wire or a very thin copper wire?
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;
}
$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).
java programming-challenge interview-questions palindrome
$endgroup$
add a comment |
$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).
java programming-challenge interview-questions palindrome
$endgroup$
$begingroup$
it is my interview question
$endgroup$
– Selman Keskin
8 hours ago
add a comment |
$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).
java programming-challenge interview-questions palindrome
$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
java programming-challenge interview-questions palindrome
edited 4 hours ago
200_success
134k21 gold badges171 silver badges440 bronze badges
134k21 gold badges171 silver badges440 bronze badges
asked 9 hours ago
Selman KeskinSelman Keskin
162 bronze badges
162 bronze badges
$begingroup$
it is my interview question
$endgroup$
– Selman Keskin
8 hours ago
add a comment |
$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
add a comment |
2 Answers
2
active
oldest
votes
$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.
$endgroup$
add a comment |
$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);
}
$endgroup$
$begingroup$
By associativity you surely meant commutativity.
$endgroup$
– vnp
6 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 startq
atmaxP / p
if larger. That could allow theP > maxP
test to be removed altogether.
$endgroup$
– Josiah
5 hours ago
$begingroup$
@vnp Yup - good catch.
$endgroup$
– AJNeufeld
4 hours ago
add a comment |
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
});
}
});
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
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
$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.
$endgroup$
add a comment |
$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.
$endgroup$
add a comment |
$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.
$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.
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
add a comment |
add a comment |
$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);
}
$endgroup$
$begingroup$
By associativity you surely meant commutativity.
$endgroup$
– vnp
6 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 startq
atmaxP / p
if larger. That could allow theP > maxP
test to be removed altogether.
$endgroup$
– Josiah
5 hours ago
$begingroup$
@vnp Yup - good catch.
$endgroup$
– AJNeufeld
4 hours ago
add a comment |
$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);
}
$endgroup$
$begingroup$
By associativity you surely meant commutativity.
$endgroup$
– vnp
6 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 startq
atmaxP / p
if larger. That could allow theP > maxP
test to be removed altogether.
$endgroup$
– Josiah
5 hours ago
$begingroup$
@vnp Yup - good catch.
$endgroup$
– AJNeufeld
4 hours ago
add a comment |
$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);
}
$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);
}
edited 4 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
6 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 startq
atmaxP / p
if larger. That could allow theP > maxP
test to be removed altogether.
$endgroup$
– Josiah
5 hours ago
$begingroup$
@vnp Yup - good catch.
$endgroup$
– AJNeufeld
4 hours ago
add a comment |
$begingroup$
By associativity you surely meant commutativity.
$endgroup$
– vnp
6 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 startq
atmaxP / p
if larger. That could allow theP > maxP
test to be removed altogether.
$endgroup$
– Josiah
5 hours ago
$begingroup$
@vnp Yup - good catch.
$endgroup$
– AJNeufeld
4 hours ago
$begingroup$
By associativity you surely meant commutativity.
$endgroup$
– vnp
6 hours ago
$begingroup$
By associativity you surely meant commutativity.
$endgroup$
– vnp
6 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
4 hours ago
$begingroup$
@vnp Yup - good catch.
$endgroup$
– AJNeufeld
4 hours ago
add a comment |
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.
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
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
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
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
$begingroup$
it is my interview question
$endgroup$
– Selman Keskin
8 hours ago