java - Optimizing the largest palindrome from product of two three digit numbers? -


i working on interview question asked in supposed write program find largest palindrome product of 2 3 digit numbers.

here question

i came brute force approach starts bottom.

public class largestpalindromequestion {      public static void main(string[] args) {         int value = 0;         (int = 100; <= 999; i++) {             (int j = i; j <= 999; j++) {                 int value1 = * j;                 if (ispalindrome(value1) && value < value1) {                     value = value1;                 }             }         }         system.out.println(value);     }      private static boolean ispalindrome(final int product) {         int p = product;         int reverse = 0;         while (p != 0) {             reverse *= 10;             reverse += p % 10;             p /= 10;         }         return reverse == product;     } } 

they asked me optimizations can in program? mentioned can try pruning search space , optimize checking step each item in search space confuse how make work in above solution?

what optimizations can in program? right executing 810000 steps find largest palindrome.

what least number of steps can execute find largest palindrome in 2 3 digit numbers?

the program looks me. make i loop count 999 down 100, , check j values give larger product current maximum.

this program able finish surprisingly soon, @ i == 952 precise. mathematical reason once solution 906609 (993 * 913) found, no longer possible find larger palindrome larger factor less square-root of 906609, 952.160....

public static void main(string[] args) {     int value = 0;     (int = 999; >= 100; i--) {         int r = value / i;         if (r >= i) {             system.out.println("we broke @ = " + i);             break;         }         (int j = i; j > r; j--) {             int value1 = * j;             if (ispalindrome(value1)) {                 value = value1;                 break;             }         }     }     system.out.println(value); } 

Comments

Popular posts from this blog

php - failed to open stream: HTTP request failed! HTTP/1.0 400 Bad Request -

java - How to filter a backspace keyboard input -

java - Show Soft Keyboard when EditText Appears -