Find the largest palindrome number made from the product of two n digit numbers in JavaScript

JavascriptWeb DevelopmentFront End TechnologyObject Oriented Programming

<p>Let us consider the number 9009. This is a special number in the sense that this is the largest palindrome number that can be formed by multiplying two 2-digit numbers (91 and 99).</p><p>We are required to write a JavaScript function that takes a number n (which specifies the number of digits). The function should simply find and return the largest palindrome number that can be formed by the multiplication of two n digit numbers.</p><h2>Example</h2><p>Following is the code &minus;</p><pre class="prettyprint notranslate">const largestPalindromic = num =&gt; { &nbsp; &nbsp;let i, n, m, d, max, sup, limit, number = 0; &nbsp; &nbsp;for (i = 1; i &lt; num; i += 1) { &nbsp; &nbsp; &nbsp; number = 10 * number + 9; &nbsp; &nbsp;}; &nbsp; &nbsp;max = number; &nbsp; &nbsp;sup = 10 * number + 9; &nbsp; &nbsp;const isPalindromic = n =&gt; { &nbsp; &nbsp; &nbsp; let p = 0, q = n, r; &nbsp; &nbsp; &nbsp; while (n &gt; 0) { &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;r = n % 10; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;p = 10 * p + r; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;n = Math.floor(n / 10); &nbsp; &nbsp; &nbsp; }; &nbsp; &nbsp; &nbsp; return p === q; &nbsp; &nbsp;}; &nbsp; &nbsp;for (n = sup * sup, m = max * max; n &gt; m; n -= 1) { &nbsp; &nbsp; &nbsp; if (isPalindromic(n)) { &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;limit = Math.ceil(Math.sqrt(n)); &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;d = sup; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;while (d &gt;= limit) { &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if (n % d === 0 &amp;&amp; n / d &gt; max) { &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;return n; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; } &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; d -= 1; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;} &nbsp; &nbsp; &nbsp; } &nbsp; &nbsp;}; } console.log(largestPalindromic(3));</pre><h2>Output</h2><p>Following is the output on console &minus;</p><pre class="result notranslate">906609</pre>
raja
Updated on 10-Dec-2020 07:47:04

Advertisements