Largest Palindrome Product in C++

C++Server Side ProgrammingProgramming

Suppose we have input n, we have to find the largest palindrome that can be made using multiplication of two n digit numbers. As the numbers are very large, we can perform mod using 1337. So if the input is say 2, then the answer will be 987, 987 = (99*91) mod 1337 = 9009 mod 1337 = 987.

To solve this, we will follow these steps −

  • maxVal := 10^n – 1
  • minVal := maxVal / 10
  • for initialize h := maxVal, when h > minVal, update (decrease h by 1), do −
    • left := h, right := 0
    • for initialize i := h, when i > 0, update right = right * 10 + i mod 10, left := left * 10, i := i / 10, do −
      • x := left + right
      • for initialize i := maxVal, when i > minVal, update (decrease i by 1), do −
        • if i < x / i, then −
          • Come out from the loop
        • if x mod i is same as 0, then −
          • return x mod 1337
  • return 9

Let us see the following implementation to get better understanding −

Example

 Live Demo

#include <bits/stdc++.h>
using namespace std;
typedef long long int lli;
class Solution {
public:
   int largestPalindrome(int n) {
      int maxVal = pow(10, n) - 1;
      int minVal = maxVal / 10;
      for(int h = maxVal; h > minVal; h--){
         lli left = h;
         lli right = 0;
         for(lli i = h; i > 0; right = right * 10 + i % 10, left*= 10, i/= 10);
         lli x = left + right;
         for(int i = maxVal; i > minVal; i--){
            if(i < x / i) break;
            if(x % i == 0) return x % 1337;
         }
      }
      return 9;
   }
};
main(){
   Solution ob;
   cout << (ob.largestPalindrome(3));
}

Input

3

Output

123
raja
Published on 01-Jun-2020 14:38:25
Advertisements