chi3f_comm5nd - 1 year ago 83
Java Question

# how to make this palindrome code more efficient and shorter

so I tried to write a program that will multiply every two numbers from 100 to 999 and check if the number is palindrome the problem is the program is not printing any output so my questions are
is the code running?if so then how to know?is there a more efficient way to this?
n.b:I'm using eclipse and jcreator and i tried to run it online but every site that i run it on prints out"time limit exceeded"
here is the code:

``````public class Palindrome_Number {

public static void main(String[] args) {
// i used the long method because the numbers will be big

long product1 = 100, product2 = 999, max = 0, palindrome = 99900, temp1 = palindrome, temp2 = 0;
//999*999 is the largest three digit # you get
// temp1=palindrome to reset temp1 to reverse it
for (; (palindrome <= 999 * 999); temp1 = palindrome) {
//to make sure that you go over each number from 1-999
if (product1 >= 100 && product1 < 999) {
product1++;
} //to reset the value of product 1 and decrease the value of temp2
else {
product1 = 100;
product2--;
}

//the while loop is made to reverse palindrome in temp2
while (temp1 != 0) {
temp2 = temp2 * 10 + temp1 % 10;
temp1 = temp1 / 10;
}

//to save the max palindrome
if (temp2 == palindrome) {
max = palindrome;
}

//resetting the values
palindrome = (product1 * product2);
temp2 = 0;
}
System.out.print(max);
}
}
``````

edit:thanks for your help debugging by printing the values at certain intervals the new code is:

``````public class Palindrome_Number
{

public static void main(String[] args)
{
long product1,product2,max=0,palindrome=99900,temp2=0;
for (product1 = 100; product1 <= 999; ++ product1)
{
for (product2 = 100; product2 <= 999; ++ product2)
{

for(long temp1=palindrome;temp1!=0;temp1/=10)
temp2 = temp2 * 10 + temp1 % 10;

if (temp2==palindrome&&(temp2>=max))max=palindrome;
temp2=0;palindrome=product1*product2;
}
}
System.out.print(max);
}
``````

}

if you can't use debugger add printout (like

`````` System.out.println("palindrome="+ palindrome);
``````

at appropriate places to monitor progress

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download