In: Computer Science
A palindromic number reads the same both ways (left-to-right and right-to-left).
The largest palindrome made from the product of two 2-digit numbers is 9,009 = 91 × 99.
The largest palindrome made from the product of two 3-digit
numbers is 906,609 = 913 × 993.
The largest palindrome made from the product of two 4-digit numbers
is 99,000,099 = 9,901 × 9,999.
1. Write a function IN JAVASCRIPT to find the largest palindrome made from the product of two 7-digit numbers.
2. What is that product?
3. How long (execution time) does it take your solution to calculate this answer?
ANSWER :
Code
public class Main { private int largestPalindrome(int n) { long startTime = System.nanoTime(); int upperBound = (int) Math.pow(10, n) - 1; int lowerBound = (int) Math.pow(10, n - 1); int maximum = Integer.MIN_VALUE; // int digit1 = 0, digit2 = 0; for (int upperIndex = upperBound; upperIndex >= lowerBound; upperIndex--) { for (int lowerIndex = upperIndex; lowerIndex >= lowerBound; lowerIndex--) { int product = upperIndex * lowerIndex; if (product < maximum) { break; } if (product > maximum && check(product)) { // digit1 = upperIndex; // digit2 = lowerIndex; maximum = product; } } } long endTime = System.nanoTime(); System.out.println("Execution time in milliseconds : " + (endTime - startTime) / 1000000); // System.out.println("Digit1 = " + digit1 + " Digit2 = " + digit2); return maximum; } private boolean check(int number) { int reverse = 0, curr = number; while (number != 0) { reverse = reverse * 10 + number % 10; number /= 10; } return curr - reverse == 0; } public static void main(String[] args) { int n = 7; Main main = new Main(); System.out.print(main.largestPalindrome(n)); } }
Output
// Uncomment the commented line to print the both the numbers
( PLEASE VOTE FOR THIS ANSWER )
I THINK IT WILL BE USEFULL TO YOU ......
PLZZZZZ COMMENT IF YOU HAVE ANY PROBLEM ........
THANK YOU ..........