Largest palindrome product: Difference between revisions

Added Easylang
(→‎{{header|C#|CSharp}}: added stretch)
(Added Easylang)
 
(30 intermediate revisions by 17 users not shown)
Line 13:
Find the largest palindrome made from the product of two n-digit numbers, where n ranges beyond 7,
<br><br>
 
=={{header|11l}}==
{{trans|Wren}}
 
<syntaxhighlight lang="11l">F reverse(=n)
V r = Int64(0)
L n > 0
r = n % 10 + r * 10
n I/= 10
R r
 
V po = Int64(10)
L(n) 2..7
V low = po * 9
po *= 10
V high = po - 1
V nextN = 0B
L(i) (high .. low).step(-1)
V j = reverse(i)
V p = i * po + j
V k = high
L k > low
I k % 10 != 5
V l = p I/ k
I l > high
L.break
I p % k == 0
print(‘Largest palindromic product of two ’n‘-digit integers: ’k‘ x ’l‘ = ’p)
nextN = 1B
L.break
k -= 2
I nextN
L.break</syntaxhighlight>
 
{{out}}
<pre>
Largest palindromic product of two 2-digit integers: 99 x 91 = 9009
Largest palindromic product of two 3-digit integers: 993 x 913 = 906609
Largest palindromic product of two 4-digit integers: 9999 x 9901 = 99000099
Largest palindromic product of two 5-digit integers: 99979 x 99681 = 9966006699
Largest palindromic product of two 6-digit integers: 999999 x 999001 = 999000000999
Largest palindromic product of two 7-digit integers: 9998017 x 9997647 = 99956644665999
</pre>
 
=={{header|ALGOL 68}}==
{{Trans|Wren}}
<langsyntaxhighlight lang="algol68">BEGIN # find the highest palindromic multiple of various sizes of numbers #
# returns n with the digits reversed #
PROC reverse = ( LONG INT v )LONG INT:
Line 61 ⟶ 104:
OD
OD
END</langsyntaxhighlight>
 
{{out}}
Line 75 ⟶ 118:
{{Trans|Ring}}
Also showing the maximum for 2 and 4 .. 7 digit numbers. Tests for a better product before testing for palindromicity.
<langsyntaxhighlight lang="algol68">BEGIN # find the highest palindromic multiple of various sizes of numbers #
PROC is pal = ( LONG INT n )BOOL:
BEGIN
Line 133 ⟶ 176:
limit start *:= 10
OD
END</langsyntaxhighlight>
{{out}}
<pre>
Line 144 ⟶ 187:
</pre>
 
=={{header|Arturo}}==
 
<syntaxhighlight lang="arturo">
palindrome?: function [n]->
(to :string n) = reverse to :string n
 
getAllMuls: function [n][
result: []
limFrom: 10^ n-1
limTo: dec 10^n
loop limFrom..limTo 'a [
loop limFrom..limTo 'b [
m: a*b
if palindrome? m ->
'result ++ @[@[a, b, a*b]]
]
]
return result
]
 
largestPal: maximum getAllMuls 3 'x -> last x
print ["Largest palindromic product of two 3-digit integers:" largestPal\0 "x" largestPal\1 "=" largestPal\2]</syntaxhighlight>
 
{{out}}
 
<pre>Largest palindromic product of two 3-digit integers: 913 x 993 = 906609</pre>
 
=={{header|AWK}}==
<syntaxhighlight lang="awk">
# syntax: GAWK -f LARGEST_PALINDROME_PRODUCT.AWK
BEGIN {
main(9)
main(99)
main(999)
main(9999)
exit(0)
}
function main(n, i,j,max_i,max_j,max_product,product) {
for (i=1; i<=n; i++) {
for (j=1; j<=n; j++) {
product = i * j
if (product > max_product) {
if (product ~ /^9/ && product ~ /9$/) {
if (product == reverse(product)) {
max_product = product
max_i = i
max_j = j
}
}
}
}
}
printf("%1d: %4s * %-4s = %d\n",length(n),max_i,max_j,max_product)
}
function reverse(str, i,rts) {
for (i=length(str); i>=1; i--) {
rts = rts substr(str,i,1)
}
return(rts)
}
</syntaxhighlight>
{{out}}
<pre>
1: 1 * 9 = 9
2: 91 * 99 = 9009
3: 913 * 993 = 906609
4: 9901 * 9999 = 99000099
</pre>
 
=={{header|Ksh}}==
<syntaxhighlight lang="ksh">
#!/bin/ksh
 
# Largest palindrome product of two 3-digit numbers
 
# # Variables:
#
typeset -si MINFACT=913 # From 'Paper & Pencil' solution
typeset -si MAXFACT=999
 
# # Functions:
#
 
# # Function _ispalindrome(n) - return 1 for palindromic number
#
function _ispalindrome {
typeset _n ; integer _n="$1"
 
(( _n != $(_flipit ${_n}) )) && return 0
return 1
}
 
# # Function _flipit(string) - return flipped string
#
function _flipit {
typeset _buf ; _buf="$1"
typeset _tmp ; unset _tmp
typeset _i ; typeset -si _i
 
for (( _i=$(( ${#_buf}-1 )); _i>=0; _i-- )); do
_tmp="${_tmp}${_buf:${_i}:1}"
done
echo "${_tmp}"
}
 
######
# main #
######
 
integer prod MAXPPROD=0
for (( i=MINFACT; i<=MAXFACT; i++)); do
for (( j=MINFACT; j<=MAXFACT; j++)); do
(( prod = i * j ))
_ispalindrome ${prod}
(( $? )) && (( prod > MAXPPROD )) && MAXPPROD=${prod}
done
done
 
print "Largest palindrome product of two 3-digit factors = ${MAXPPROD}"
</syntaxhighlight>
{{out}}<pre>
Largest palindrome product of two 3-digit factors = 906609</pre>
 
=={{header|C#|CSharp}}==
===Main Task===
{{trans|Paper & Pencil}}
<langsyntaxhighlight lang="csharp">using System;
class Program {
 
Line 185 ⟶ 350:
Console.Write("{0} {1} μs", bs, sw.Elapsed.TotalMilliseconds * 1000.0);
}
}</langsyntaxhighlight>
{{out|Output @ Tio.run}}
<pre>913 x 993 = 906609 245.2 μs</pre>
 
===Stretch===
<syntaxhighlight lang="csharp">using System;
Showing results for 2 through 10 digit factors.
<lang csharp>using System;
 
class Program {
Line 223 ⟶ 387:
if (isPal(p)) {
if (p > bp) bp = p;
bs = string.Format(" {0,2} {1,10} x {12,-10} = {23}{4}", n, y, z - c, new string(' ', 10 - n), bp); }
p -= yy; c += 10; }
y -= ld == 7 ? 44 : 22; }
Line 229 ⟶ 393:
 
static void Main(string[] args) {
Console.WriteLine("digs factor factor palindrome");
var sw = System.Diagnostics.Stopwatch.StartNew();
for (int i = 2, h = 1; i <= 10; h = ++i >> 1) {
Line 235 ⟶ 400:
a = new string('9', h) + new string('0', (h) - 1) + "1",
c = new string('9', h) + new string('0', i) + new string('9', h);
Console.WriteLine(" {0,2} {1,10} x {12,-10} = {23}{4}", i, a, b, new string(' ', 10 - i), c); }
else doOne(i);
}
Line 241 ⟶ 406:
Console.Write("{0} sec", sw.Elapsed.TotalSeconds);
}
}</langsyntaxhighlight>
{{out|Output @ Tio.run}}
Showing results for 2 through 10 digit factors.
<pre>91 x 99 = 9009
<pre>digs factor factor palindrome
913 x 993 = 906609
2 91 x 99 = 9009
9901 x 9999 = 99000099
3 913 x 993 = 906609
99979 x 99681 = 9966006699
4 9901 x 9999 = 99000099
999001 x 999999 = 999000000999
5 99979 x 99681 = 9966006699
9997647 x 9998017 = 99956644665999
6 999001 x 999999 = 999000000999
99990001 x 99999999 = 9999000000009999
7 9997647 x 9998017 = 99956644665999
999920317 x 999980347 = 999900665566009999
8 99990001 x 99999999 = 9999000000009999
9999900001 x 9999999999 = 99999000000000099999
9 999920317 x 999980347 = 999900665566009999
2.2502339 sec</pre>Wow! how did that go so fast? The results for the even-number-of-digit factors were manufactured by string manipulation instead of calculation (since the pattern was obvious). This algorithm can easily be adapted to BigIntegers for higher n-digit factors, but the execution time is unspectacular.
10 9999900001 x 9999999999 = 99999000000000099999
2.1622142 sec</pre>Wow! how did that go so fast? The results for the even-number-of-digit factors were manufactured by string manipulation instead of calculation (since the pattern was obvious). This algorithm can easily be adapted to BigIntegers for higher n-digit factors, but the execution time is unspectacular.
 
 
=={{header|Delphi}}==
{{works with|Delphi|6.0}}
{{libheader|uses Windows,SysUtils,StdCtrls,Math}}
 
 
<syntaxhighlight lang="Delphi">
 
type TProgress = procedure(Percent: integer);
 
function ReverseNum(N: int64): int64;
{Reverse the digit order of a number}
begin
Result:=0;
while N>0 do
begin
Result:=(Result*10)+(N mod 10);
N:=N div 10;
end;
end;
 
 
function IsPalindrome(N: int64): boolean;
{If the number is the same in }
{reverse order it is a palindrome}
var N1: int64;
begin
N1:=ReverseNum(N);
Result:=N = N1;
end;
 
procedure ShowPalindrome(Memo: TMemo; D,N1,N2: int64);
begin
Memo.Lines.Add(Format('%5D %5D %5D %10D',[D,N1,N2,N1 * N2]));
end;
 
 
procedure FindPalindromes(Digits: integer; var C1,C2: int64; Prog: TProgress);
{Find the largest palindrome derrived from two}
{ terms with the specified number of digits}
var I,J: cardinal;
var Prd,MinNum,MaxNum,Best: int64;
begin
Best:=0;
{Find the minimum and maximum values}
{ with the specified number of digits}
MinNum:=Trunc(Power(10,Digits-1));
MaxNum:=Trunc(Power(10,Digits))-1;
 
for I:=MinNum to MaxNum do
begin
{We can eliminate even factors and number ending in 5}
if ((I and 1)=0) or ((I mod 10)=5) then continue;
for J:=I+1 to MaxNum do
begin
{We can eliminate even factors and number ending in 5}
if ((J and 1)=0) or ((J mod 10)=5) then continue;
Prd:=I * J;
if not IsPalindrome(Prd) then continue;
if Assigned(Prog) then Prog(MulDiv(100,I-MinNum,MaxNum-MinNum));
{Save the largest palindromes}
if Prd>Best then
begin
Best:=Prd;
C1:=I; C2:=J;
end;
end;
end;
end;
 
 
procedure FindPalindromeMax(Memo: TMemo; Prog: TProgress);
var N1,N2: Int64;
var I: integer;
begin
Memo.Lines.Add('Digits F1 F2 Palindrome');
Memo.Lines.Add('-------------------------------');
for I:=2 to 4 do
begin
FindPalindromes(I,N1,N2,Prog);
ShowPalindrome(Memo,I,N1,N2);
end;
end;
 
</syntaxhighlight>
{{out}}
<pre>
Digits F1 F2 Palindrome
-------------------------------
2 91 99 9009
3 913 993 906609
4 9901 9999 99000099
</pre>
 
=={{header|EasyLang}}==
<syntaxhighlight>
fastfunc rev n .
while n > 0
r = r * 10 + n mod 10
n = n div 10
.
return r
.
for i = 100 to 999
for j = i to 999
p = i * j
if p > max and p = rev p
max = p
.
.
.
</syntaxhighlight>
{{out}}
<pre>
906609
</pre>
 
=={{header|F_Sharp|F#}}==
<langsyntaxhighlight lang="fsharp">
// Largest palindrome product. Nigel Galloway: November 3rd., 2021
let fN g=let rec fN g=[yield g%10; if g>=10 then yield! fN(g/10)] in let n=fN g in n=List.rev n
printfn "%d" ([for n in 100..999 do for g in n..999->n*g]|>List.filter fN|>List.max)
</syntaxhighlight>
</lang>
{{out}}
<pre>
906609
</pre>
 
=={{header|FreeBASIC}}==
===Version 1===
<syntaxhighlight lang="freebasic">function make_pal( n as ulongint ) as ulongint
'turn a number into a palindrom with twice as many digits
dim as string ns, ret
ns = str(n) : ret = ns
for i as uinteger = len(ns) to 1 step -1
ret += mid(ns, i, 1)
next i
return val(ret)
end function
 
function has_dig( n as ulongint, d as uinteger ) as boolean
'does the number n have d decimal digits?
if 10^(d-1)<=n and n<10^d then return true else return false
end function
 
dim as integer np
 
for d as uinteger = 2 to 7
for n as ulongint = 10^d - 1 to 10^(d-1) step -1 'count down from 999...
'since the first good number we encounter
'must be the highest
np = make_pal( n ) 'produce a 2d-digit palindrome from it
for f as ulongint = 10^d - 1 to 10^(d-1) step -1 'look for highest d-digit factor
if np mod f = 0 then
if has_dig( np/f, d ) then 'if np/f also has d digits we are done :)
print f;" *";np/f;" =";np
goto nextd
end if
end if
next f
next n
nextd: 'yes, I used a goto. sue me.
next d</syntaxhighlight>
{{out}}
<pre>99 * 91 = 9009
993 * 913 = 906609
9999 * 9901 = 99000099
99979 * 99681 = 9966006699
999999 * 999001 = 999000000999
9998017 * 9997647 = 99956644665999</pre>
===Version 2===
This version is based on Version 1 with only a few changes and some extra code based on the fact that one divisor can be divided by 11, this speeds it even more up and a option for using goto, exit or continue. highest n is 9, (highest possible for unsigned 64bit integers).
<syntaxhighlight lang="freebasic">' version 07-10-2021
' compile with: fbc -s console
 
' Now you can choice, no speed changes for all 3
' 1: use goto
' 2: use exit
' 3: use continue
#Define Option_ 1 ' set option_ to 1, 2 or 3. for all other value's uses 1
 
Function make_pal( n As UInteger ) As ULongInt
'turn a number into a palindrom with twice as many digits
Dim As String ns = Str(n), ret = ns
For i As UInteger = Len(ns) To 1 Step -1
ret += Mid(ns, i, 1)
Next i
Return ValULng(ret)
End Function
 
Dim As ULongInt np, tmp
Dim As Double t1 =Timer
For d As UInteger = 2 To 9
For n As UInteger = 10^d -2 To 10^(d -1) Step -1
np = make_pal( n )
tmp = Sqr(np)
tmp = tmp - (10^d - 1 - tmp)
tmp = tmp - tmp Mod 11
If (tmp And 1) = 0 Then tmp = tmp + 11
For f As UInteger = tmp To 10^d -1 Step 22
If np Mod f = 0 Then
If np \ f > (10^d) Then Continue For
Print f; " * "; np \ f; " = "; np
#If (option_ = 2)
Exit For, For
#ElseIf (option_ = 3)
Continue For, For, For
#Else
GoTo nextd
#EndIf
End If
Next f
Next n
#If (option_ <> 2 Or option_ <> 3)
nextd:
#EndIf
Next d
 
Print Timer-t1
' empty keyboard buffer
While InKey <> "" : Wend
Print : Print "hit any key to end program"
Sleep
End</syntaxhighlight>
{{out}}
<pre>99 * 91 = 9009
993 * 913 = 906609
9999 * 9901 = 99000099
99979 * 99681 = 9966006699
999999 * 999001 = 999000000999
9998017 * 9997647 = 99956644665999
99999999 * 99990001 = 9999000000009999
999980347 * 999920317 = 999900665566009999</pre>
 
=={{header|Go}}==
{{trans|Wren}}
18 digit integers are within the range of Go's uint64 type though finding the result for 9-digit number products takes a while - around 15 seconds on my machine.
<langsyntaxhighlight lang="go">package main
 
import "fmt"
Line 308 ⟶ 698:
}
}
}</langsyntaxhighlight>
 
{{out}}
Line 321 ⟶ 711:
Largest palindromic product of two 9-digit integers: 999980347 x 999920317 = 999900665566009999
</pre>
 
=={{header|jq}}==
'''Adapted from [[#Wren|Wren]]'''
{{works with|jq}}
'''Works with gojq, the Go implementation of jq'''
<syntaxhighlight lang="jq">def reverseNumber:
tostring|explode|reverse|implode|tonumber;
def task:
{ pow: 10}
| foreach range(2;8) as $n (.;
(.pow * 9) as $low
| .pow *= 10
| (.pow - 1) as $high
| .emit = null
| .nextN = false
| label $out
| foreach range($high; $low - 1; -1) as $i (.;
($i|reverseNumber) as $j
| ($i * .pow + $j) as $p
# k can't be even nor end in 5 to produce a product ending in 9
| .k = $high
| .done = false
| until(.k <= $low or .done;
if (.k % 10 != 5)
then ($p / .k) as $l
| if $l > $high
then .done = true
elif $p % .k == 0
then .emit = "Largest palindromic product of two \($n)-digit integers: \(.k) x \($l) = \($p)"
| .nextN = true
| .done = true
else .
end
else .
end
| .k += -2 )
| if .nextN then ., break $out else . end;
select(.emit) );
.emit ) ;
 
task</syntaxhighlight>
{{out}}
<pre>
Largest palindromic product of two 2-digit integers: 99 x 91 = 9009
Largest palindromic product of two 3-digit integers: 993 x 913 = 906609
Largest palindromic product of two 4-digit integers: 9999 x 9901 = 99000099
Largest palindromic product of two 5-digit integers: 99979 x 99681 = 9966006699
Largest palindromic product of two 6-digit integers: 999999 x 999001 = 999000000999
Largest palindromic product of two 7-digit integers: 9998017 x 9997647 = 99956644665999
</pre>
 
 
=={{header|Julia}}==
<langsyntaxhighlight lang="julia">using Primes
 
function twoprodpal(factorlength)
Line 356 ⟶ 798:
twoprodpal(i)
end
</langsyntaxhighlight>{{out}}
<pre>
For factor length 2, 91 * 99 = 9009
Line 369 ⟶ 811:
For factor length 11, 99999943851 * 99999996349 = 9999994020000204999999
For factor length 12, 999999000001 * 999999999999 = 999999000000000000999999
</pre>
 
=== Faster version ===
{{trans|Python}}
<syntaxhighlight lang="julia">""" taken from https://leetcode.com/problems/largest-palindrome-product/discuss/150954/Fast-algorithm-by-constrains-on-tail-digits """
 
const T = [Set([(0, 0)])]
 
function double(it)
arr = empty(it)
for p in it
push!(arr, p, reverse(p))
end
return arr
end
 
""" Construct a pair of n-digit numbers such that their product ends with 99...9 pattern """
function tails(n)
if length(T) <= n
l = Set()
for i in 0:9, j in i:9
I = i * 10^(n-1)
J = j * 10^(n-1)
it = collect(tails(n - 1))
I != J && (it = double(it))
for (t1, t2) in it
if ((I + t1) * (J + t2) + 1) % 10^n == 0
push!(l, (I + t1, J + t2))
end
end
end
push!(T, l)
end
return T[n + 1]
end
 
""" find the largest palindrome that is a product of n-digit numbers """
function largestpalindrome(n)
m, tail = 0, n ÷ 2
head = n - tail
up = 10^head
for L in 1 : 9 * 10^(head-1)
# Consider small shell (up-L)^2 < (up-i)*(up-j) <= (up-L)^2, 1<=i<=L<=j
m, sol = 0, (0, 0)
for i in 1:L
lo = max(Int128(i), Int128(up - (up - L + 1)^2 ÷ (up - i)) + 1)
hi = Int128(up - (up - L)^2 ÷ (up - i))
for j in lo:hi
I = (up - i) * 10^tail
J = (up - j) * 10^tail
it = collect(tails(tail))
I != J && (it = double(it))
for (t1, t2) in it
val = (I + t1) * (J + t2)
s = string(val)
if s == reverse(s) && val > m
sol = (I + t1, J + t2)
m = val
end
end
end
end
if m > 0
println(lpad(n, 2), " ", lpad(m % 1337, 4), " $sol $(sol[1] * sol[2])")
return m % 1337
end
end
return 0
end
 
@time for k in 1:16
largestpalindrome(k)
end
</syntaxhighlight>{{out}}
<pre>
1 9 (9, 1) 9
2 987 (91, 99) 9009
3 123 (993, 913) 906609
4 597 (9901, 9999) 99000099
5 677 (99979, 99681) 9966006699
6 1218 (999001, 999999) 999000000999
7 877 (9998017, 9997647) 99956644665999
8 475 (99990001, 99999999) 9999000000009999
9 1226 (999980347, 999920317) 999900665566009999
10 875 (9999986701, 9999996699) 99999834000043899999
11 108 (99999943851, 99999996349) 9999994020000204999999
12 378 (999999000001, 999999999999) 999999000000000000999999
13 1097 (9999999993349, 9999996340851) 99999963342000024336999999
14 959 (99999990000001, 99999999999999) 9999999000000000000009999999
15 465 (999999998341069, 999999975838971) 999999974180040040081479999999
16 51 (9999999900000001, 9999999999999999) 99999999000000000000000099999999
62.575515 seconds (241.50 M allocations: 16.491 GiB, 25.20% gc time, 0.07% compilation time)
</pre>
 
=={{header|Mathematica}} / {{header|Wolfram Language}}==
<syntaxhighlight lang="mathematica">palindromeQ[n_] := (* faster than built in test PalindromeQ *)
Block[{digits = IntegerDigits@n}, digits == Reverse[digits]]
 
nextPair[n_] := (* outputs next pair of candidate divisors *)
Block[{next =
NestWhile[# - 11 &, n, ! MemberQ[{1, 3, 7, 9}, Mod[#, 10]] &],
len = Last@RealDigits@n},
{next, 10^len - Switch[Mod[next, 10], 1, 1, 3, 7, 7, 3, 9, 9]}]
 
search[n_] :=
Block[{resetLimit = 10^(n - Floor[n/2]) (10^Floor[n/2] - 1), cands},
cands =
Partition[
Flatten[
Reap[
NestWhile[(If[palindromeQ[Times @@ #], Sow[#]];
If[Last@# < resetLimit,
nextPair[First@# - 11], # - {0, 10}]) &,
nextPair@If[EvenQ@n, 10^n - 1, 10^n - 21],
First@# > resetLimit &]]], 2];
Flatten@cands[[Ordering[Times @@@ cands, -1]]]]
 
Grid[Join[{{"factors", "largest palindrome"}}, {#, Times @@ #} & /@
Table[search[n], {n, 2, 7}]], Alignment -> {Left, Baseline}]</syntaxhighlight>
 
{{out}}<pre>
factors largest palindrome
{99,91} 9009
{913,993} 906609
{9999,9901} 99000099
{99979,99681} 9966006699
{999999,999001} 999000000999
{9997647,9998017} 99956644665999
</pre>
 
=={{header|Paper & Pencil}}==
<syntaxhighlight lang="text">find two 3-digit factors, that when multiplied together, yield the highest 6-digit palindrome.
 
lowest possible 6 digit palindrome starting with 9 is 900009
Line 399 ⟶ 969:
979 x 931 = 911449‬, not a palindrome, so continue
979 x 921 = 901659‬, not a palindrome, and less than the best found so far, so stop
done because 979 + 22 = 1001</langsyntaxhighlight>
 
=={{header|Perl}}==
{{libheader|ntheory}}
<langsyntaxhighlight lang="perl">use strict;
use warnings;
use feature 'say';
Line 415 ⟶ 985:
say "Largest palindromic product of two @{[$l]}-digit integers: $f[1] × $f[0] = $p" and last LOOP;
}
}</langsyntaxhighlight>
{{out}}
<pre>Largest palindromic product of two 2-digit integers: 91 × 99 = 9009
Line 423 ⟶ 993:
Largest palindromic product of two 6-digit integers: 999001 × 999999 = 999000000999
Largest palindromic product of two 7-digit integers: 9997647 × 9998017 = 99956644665999</pre>
 
=={{header|Phix}}==
{{libheader|Phix/online}}
Translated from python by Lucy_Hedgehog as found on page 5 of the project euler discussion page (dated 25 Sep 2011),
and further optimised as per the C# comments (on this very rosettacode page).
You can run this online [http://phix.x10.mx/p2js/Largest_palindrome_product.htm here].
<!--<syntaxhighlight lang="phix">(phixonline)-->
<span style="color: #000080;font-style:italic;">-- demo\rosetta\Largest_palindrome_product.exw</span>
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
<span style="color: #7060A8;">requires</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"1.0.1"</span><span style="color: #0000FF;">)</span> <span style="color: #000080;font-style:italic;">-- (mpz_fdiv_qr(), mpz_si_sub() added to mpfr.js, mpz_mod_ui(), mpz_fdiv_q_ui(), mpz_fdiv_r(), mpz_fdiv_ui() fixed)</span>
<span style="color: #008080;">include</span> <span style="color: #004080;">mpfr</span><span style="color: #0000FF;">.</span><span style="color: #000000;">e</span>
<span style="color: #008080;">function</span> <span style="color: #000000;">ispalindrome</span><span style="color: #0000FF;">(</span><span style="color: #004080;">mpz</span> <span style="color: #000000;">x</span><span style="color: #0000FF;">)</span>
<span style="color: #004080;">string</span> <span style="color: #000000;">s</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">mpz_get_str</span><span style="color: #0000FF;">(</span><span style="color: #000000;">x</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">return</span> <span style="color: #000000;">s</span> <span style="color: #0000FF;">==</span> <span style="color: #7060A8;">reverse</span><span style="color: #0000FF;">(</span><span style="color: #000000;">s</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
<span style="color: #008080;">function</span> <span style="color: #000000;">inverse</span><span style="color: #0000FF;">(</span><span style="color: #004080;">mpz</span> <span style="color: #000000;">x</span><span style="color: #0000FF;">,</span> <span style="color: #004080;">integer</span> <span style="color: #000000;">m</span><span style="color: #0000FF;">)</span>
<span style="color: #000080;font-style:italic;">-- Compute the modular inverse of x modulo power(10,m).
-- Return -1 if the inverse does not exist.
-- This function uses Hensel lifting.</span>
<span style="color: #004080;">integer</span> <span style="color: #000000;">a</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{-</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">1</span><span style="color: #0000FF;">,</span> <span style="color: #0000FF;">-</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">7</span><span style="color: #0000FF;">,</span> <span style="color: #0000FF;">-</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span> <span style="color: #0000FF;">-</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span> <span style="color: #0000FF;">-</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">3</span><span style="color: #0000FF;">,</span> <span style="color: #0000FF;">-</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">9</span><span style="color: #0000FF;">}[</span><span style="color: #7060A8;">mpz_fdiv_ui</span><span style="color: #0000FF;">(</span><span style="color: #000000;">x</span><span style="color: #0000FF;">,</span><span style="color: #000000;">10</span><span style="color: #0000FF;">)+</span><span style="color: #000000;">1</span><span style="color: #0000FF;">]</span>
<span style="color: #008080;">if</span> <span style="color: #000000;">a</span><span style="color: #0000FF;">!=-</span><span style="color: #000000;">1</span> <span style="color: #008080;">then</span>
<span style="color: #004080;">mpz</span> <span style="color: #000000;">ax</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">mpz_init</span><span style="color: #0000FF;">()</span>
<span style="color: #008080;">while</span> <span style="color: #004600;">true</span> <span style="color: #008080;">do</span>
<span style="color: #7060A8;">mpz_mul_si</span><span style="color: #0000FF;">(</span><span style="color: #000000;">ax</span><span style="color: #0000FF;">,</span><span style="color: #000000;">x</span><span style="color: #0000FF;">,</span><span style="color: #000000;">a</span><span style="color: #0000FF;">)</span>
<span style="color: #0000FF;">{}</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">mpz_mod_ui</span><span style="color: #0000FF;">(</span><span style="color: #000000;">ax</span><span style="color: #0000FF;">,</span><span style="color: #000000;">ax</span><span style="color: #0000FF;">,</span><span style="color: #000000;">m</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">if</span> <span style="color: #7060A8;">mpz_cmp_si</span><span style="color: #0000FF;">(</span><span style="color: #000000;">ax</span><span style="color: #0000FF;">,</span><span style="color: #000000;">1</span><span style="color: #0000FF;">)==</span><span style="color: #000000;">0</span> <span style="color: #008080;">then</span> <span style="color: #008080;">exit</span> <span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #7060A8;">mpz_si_sub</span><span style="color: #0000FF;">(</span><span style="color: #000000;">ax</span><span style="color: #0000FF;">,</span><span style="color: #000000;">2</span><span style="color: #0000FF;">,</span><span style="color: #000000;">ax</span><span style="color: #0000FF;">)</span>
<span style="color: #7060A8;">mpz_mul_si</span><span style="color: #0000FF;">(</span><span style="color: #000000;">ax</span><span style="color: #0000FF;">,</span><span style="color: #000000;">ax</span><span style="color: #0000FF;">,</span><span style="color: #000000;">a</span><span style="color: #0000FF;">)</span>
<span style="color: #000000;">a</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">mpz_fdiv_q_ui</span><span style="color: #0000FF;">(</span><span style="color: #000000;">ax</span><span style="color: #0000FF;">,</span><span style="color: #000000;">ax</span><span style="color: #0000FF;">,</span><span style="color: #000000;">m</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">while</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #008080;">return</span> <span style="color: #000000;">a</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
<span style="color: #008080;">function</span> <span style="color: #000000;">pal2</span><span style="color: #0000FF;">(</span><span style="color: #004080;">integer</span> <span style="color: #000000;">n</span><span style="color: #0000FF;">)</span>
<span style="color: #7060A8;">assert</span><span style="color: #0000FF;">(</span><span style="color: #000000;">n</span><span style="color: #0000FF;">></span><span style="color: #000000;">1</span><span style="color: #0000FF;">)</span>
<span style="color: #004080;">mpz</span> <span style="color: #0000FF;">{</span><span style="color: #000000;">best</span><span style="color: #0000FF;">,</span><span style="color: #000000;">factor</span><span style="color: #0000FF;">,</span><span style="color: #000000;">y</span><span style="color: #0000FF;">,</span><span style="color: #000000;">r</span><span style="color: #0000FF;">}</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">mpz_inits</span><span style="color: #0000FF;">(</span><span style="color: #000000;">4</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">if</span> <span style="color: #7060A8;">even</span><span style="color: #0000FF;">(</span><span style="color: #000000;">n</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">then</span>
<span style="color: #000080;font-style:italic;">// (as per the C# comments)</span>
<span style="color: #7060A8;">mpz_ui_pow_ui</span><span style="color: #0000FF;">(</span><span style="color: #000000;">factor</span><span style="color: #0000FF;">,</span><span style="color: #000000;">10</span><span style="color: #0000FF;">,</span><span style="color: #000000;">n</span><span style="color: #0000FF;">/</span><span style="color: #000000;">2</span><span style="color: #0000FF;">)</span>
<span style="color: #7060A8;">mpz_sub_si</span><span style="color: #0000FF;">(</span><span style="color: #000000;">factor</span><span style="color: #0000FF;">,</span><span style="color: #000000;">factor</span><span style="color: #0000FF;">,</span><span style="color: #000000;">1</span><span style="color: #0000FF;">)</span>
<span style="color: #7060A8;">mpz_ui_pow_ui</span><span style="color: #0000FF;">(</span><span style="color: #000000;">best</span><span style="color: #0000FF;">,</span><span style="color: #000000;">10</span><span style="color: #0000FF;">,</span><span style="color: #000000;">n</span><span style="color: #0000FF;">/</span><span style="color: #000000;">2</span><span style="color: #0000FF;">*</span><span style="color: #000000;">3</span><span style="color: #0000FF;">)</span>
<span style="color: #7060A8;">mpz_mul</span><span style="color: #0000FF;">(</span><span style="color: #000000;">best</span><span style="color: #0000FF;">,</span><span style="color: #000000;">best</span><span style="color: #0000FF;">,</span><span style="color: #000000;">factor</span><span style="color: #0000FF;">)</span>
<span style="color: #7060A8;">mpz_add</span><span style="color: #0000FF;">(</span><span style="color: #000000;">best</span><span style="color: #0000FF;">,</span><span style="color: #000000;">best</span><span style="color: #0000FF;">,</span><span style="color: #000000;">factor</span><span style="color: #0000FF;">)</span>
<span style="color: #7060A8;">assert</span><span style="color: #0000FF;">(</span><span style="color: #000000;">ispalindrome</span><span style="color: #0000FF;">(</span><span style="color: #000000;">best</span><span style="color: #0000FF;">))</span>
<span style="color: #7060A8;">mpz_ui_pow_ui</span><span style="color: #0000FF;">(</span><span style="color: #000000;">factor</span><span style="color: #0000FF;">,</span><span style="color: #000000;">10</span><span style="color: #0000FF;">,</span><span style="color: #000000;">n</span><span style="color: #0000FF;">)</span>
<span style="color: #7060A8;">mpz_sub_si</span><span style="color: #0000FF;">(</span><span style="color: #000000;">factor</span><span style="color: #0000FF;">,</span><span style="color: #000000;">factor</span><span style="color: #0000FF;">,</span><span style="color: #000000;">1</span><span style="color: #0000FF;">)</span>
<span style="color: #7060A8;">assert</span><span style="color: #0000FF;">(</span><span style="color: #000000;">ispalindrome</span><span style="color: #0000FF;">(</span><span style="color: #000000;">factor</span><span style="color: #0000FF;">))</span>
<span style="color: #008080;">else</span>
<span style="color: #000080;font-style:italic;">// Get a lower bound:</span>
<span style="color: #004080;">integer</span> <span style="color: #000000;">k</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">floor</span><span style="color: #0000FF;">(</span><span style="color: #000000;">n</span><span style="color: #0000FF;">/</span><span style="color: #000000;">2</span><span style="color: #0000FF;">)</span>
<span style="color: #004080;">mpz</span> <span style="color: #0000FF;">{</span><span style="color: #000000;">maxf</span><span style="color: #0000FF;">,</span><span style="color: #000000;">maxf11</span><span style="color: #0000FF;">,</span><span style="color: #000000;">minf</span><span style="color: #0000FF;">,</span><span style="color: #000000;">x</span><span style="color: #0000FF;">,</span><span style="color: #000000;">t</span><span style="color: #0000FF;">,</span><span style="color: #000000;">maxy</span><span style="color: #0000FF;">,</span><span style="color: #000000;">p</span><span style="color: #0000FF;">}</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">mpz_inits</span><span style="color: #0000FF;">(</span><span style="color: #000000;">7</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">while</span> <span style="color: #004600;">true</span> <span style="color: #008080;">do</span>
<span style="color: #7060A8;">mpz_ui_pow_ui</span><span style="color: #0000FF;">(</span><span style="color: #000000;">maxf</span><span style="color: #0000FF;">,</span><span style="color: #000000;">10</span><span style="color: #0000FF;">,</span><span style="color: #000000;">n</span><span style="color: #0000FF;">)</span>
<span style="color: #7060A8;">mpz_sub_si</span><span style="color: #0000FF;">(</span><span style="color: #000000;">maxf</span><span style="color: #0000FF;">,</span><span style="color: #000000;">maxf</span><span style="color: #0000FF;">,</span><span style="color: #000000;">1</span><span style="color: #0000FF;">)</span>
<span style="color: #7060A8;">mpz_sub_si</span><span style="color: #0000FF;">(</span><span style="color: #000000;">maxf11</span><span style="color: #0000FF;">,</span><span style="color: #000000;">maxf</span><span style="color: #0000FF;">,</span><span style="color: #000000;">11</span><span style="color: #0000FF;">)</span>
<span style="color: #0000FF;">{}</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">mpz_fdiv_q_ui</span><span style="color: #0000FF;">(</span><span style="color: #000000;">maxf11</span><span style="color: #0000FF;">,</span><span style="color: #000000;">maxf11</span><span style="color: #0000FF;">,</span><span style="color: #000000;">22</span><span style="color: #0000FF;">)</span>
<span style="color: #7060A8;">mpz_mul_si</span><span style="color: #0000FF;">(</span><span style="color: #000000;">maxf11</span><span style="color: #0000FF;">,</span><span style="color: #000000;">maxf11</span><span style="color: #0000FF;">,</span><span style="color: #000000;">22</span><span style="color: #0000FF;">)</span>
<span style="color: #7060A8;">mpz_add_si</span><span style="color: #0000FF;">(</span><span style="color: #000000;">maxf11</span><span style="color: #0000FF;">,</span><span style="color: #000000;">maxf11</span><span style="color: #0000FF;">,</span><span style="color: #000000;">11</span><span style="color: #0000FF;">)</span>
<span style="color: #7060A8;">mpz_ui_pow_ui</span><span style="color: #0000FF;">(</span><span style="color: #000000;">minf</span><span style="color: #0000FF;">,</span><span style="color: #000000;">10</span><span style="color: #0000FF;">,</span><span style="color: #000000;">n</span><span style="color: #0000FF;">-</span><span style="color: #000000;">k</span><span style="color: #0000FF;">)</span>
<span style="color: #7060A8;">mpz_sub</span><span style="color: #0000FF;">(</span><span style="color: #000000;">minf</span><span style="color: #0000FF;">,</span><span style="color: #000000;">maxf</span><span style="color: #0000FF;">,</span><span style="color: #000000;">minf</span><span style="color: #0000FF;">)</span>
<span style="color: #7060A8;">mpz_add_si</span><span style="color: #0000FF;">(</span><span style="color: #000000;">minf</span><span style="color: #0000FF;">,</span><span style="color: #000000;">minf</span><span style="color: #0000FF;">,</span><span style="color: #000000;">2</span><span style="color: #0000FF;">)</span>
<span style="color: #7060A8;">mpz_mul</span><span style="color: #0000FF;">(</span><span style="color: #000000;">best</span><span style="color: #0000FF;">,</span><span style="color: #000000;">minf</span><span style="color: #0000FF;">,</span><span style="color: #000000;">minf</span><span style="color: #0000FF;">)</span>
<span style="color: #7060A8;">mpz_set_si</span><span style="color: #0000FF;">(</span><span style="color: #000000;">factor</span><span style="color: #0000FF;">,</span><span style="color: #000000;">0</span><span style="color: #0000FF;">)</span>
<span style="color: #000080;font-style:italic;">// This palindrome starts with k 9's.
// Hence the largest palindrom must also start with k 9's and
// therefore end with k 9's.
// Thus, if p = x * y is the solution then
// x * y + 1 is divisible by m.</span>
<span style="color: #004080;">integer</span> <span style="color: #000000;">m</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">power</span><span style="color: #0000FF;">(</span><span style="color: #000000;">10</span><span style="color: #0000FF;">,</span><span style="color: #000000;">k</span><span style="color: #0000FF;">)</span> <span style="color: #000080;font-style:italic;">-- (should not exceed 1e8)</span>
<span style="color: #7060A8;">mpz_set</span><span style="color: #0000FF;">(</span><span style="color: #000000;">x</span><span style="color: #0000FF;">,</span><span style="color: #000000;">maxf11</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">while</span> <span style="color: #7060A8;">mpz_cmp_si</span><span style="color: #0000FF;">(</span><span style="color: #000000;">x</span><span style="color: #0000FF;">,</span><span style="color: #000000;">1</span><span style="color: #0000FF;">)>=</span><span style="color: #000000;">0</span> <span style="color: #008080;">do</span>
<span style="color: #7060A8;">mpz_mul</span><span style="color: #0000FF;">(</span><span style="color: #000000;">t</span><span style="color: #0000FF;">,</span><span style="color: #000000;">x</span><span style="color: #0000FF;">,</span><span style="color: #000000;">maxf</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">if</span> <span style="color: #7060A8;">mpz_cmp</span><span style="color: #0000FF;">(</span><span style="color: #000000;">t</span><span style="color: #0000FF;">,</span><span style="color: #000000;">best</span><span style="color: #0000FF;">)=-</span><span style="color: #000000;">1</span> <span style="color: #008080;">then</span> <span style="color: #008080;">exit</span> <span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #004080;">integer</span> <span style="color: #000000;">ry</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">inverse</span><span style="color: #0000FF;">(</span><span style="color: #000000;">x</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">m</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">if</span> <span style="color: #000000;">ry</span><span style="color: #0000FF;">!=-</span><span style="color: #000000;">1</span> <span style="color: #008080;">then</span>
<span style="color: #7060A8;">mpz_add_si</span><span style="color: #0000FF;">(</span><span style="color: #000000;">maxy</span><span style="color: #0000FF;">,</span><span style="color: #000000;">maxf</span><span style="color: #0000FF;">,</span><span style="color: #000000;">1</span><span style="color: #0000FF;">-</span><span style="color: #000000;">ry</span><span style="color: #0000FF;">)</span>
<span style="color: #7060A8;">mpz_mul</span><span style="color: #0000FF;">(</span><span style="color: #000000;">p</span><span style="color: #0000FF;">,</span><span style="color: #000000;">maxy</span><span style="color: #0000FF;">,</span><span style="color: #000000;">x</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">while</span> <span style="color: #7060A8;">mpz_cmp</span><span style="color: #0000FF;">(</span><span style="color: #000000;">p</span><span style="color: #0000FF;">,</span><span style="color: #000000;">best</span><span style="color: #0000FF;">)></span><span style="color: #000000;">0</span> <span style="color: #008080;">do</span>
<span style="color: #008080;">if</span> <span style="color: #000000;">ispalindrome</span><span style="color: #0000FF;">(</span><span style="color: #000000;">p</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">then</span>
<span style="color: #7060A8;">mpz_set</span><span style="color: #0000FF;">(</span><span style="color: #000000;">best</span><span style="color: #0000FF;">,</span><span style="color: #000000;">p</span><span style="color: #0000FF;">)</span>
<span style="color: #7060A8;">mpz_set</span><span style="color: #0000FF;">(</span><span style="color: #000000;">factor</span><span style="color: #0000FF;">,</span><span style="color: #000000;">x</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #7060A8;">mpz_mul_si</span><span style="color: #0000FF;">(</span><span style="color: #000000;">t</span><span style="color: #0000FF;">,</span><span style="color: #000000;">x</span><span style="color: #0000FF;">,</span><span style="color: #000000;">m</span><span style="color: #0000FF;">)</span>
<span style="color: #7060A8;">mpz_sub</span><span style="color: #0000FF;">(</span><span style="color: #000000;">p</span><span style="color: #0000FF;">,</span><span style="color: #000000;">p</span><span style="color: #0000FF;">,</span><span style="color: #000000;">t</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">while</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #7060A8;">mpz_sub_si</span><span style="color: #0000FF;">(</span><span style="color: #000000;">x</span><span style="color: #0000FF;">,</span><span style="color: #000000;">x</span><span style="color: #0000FF;">,</span><span style="color: #000000;">22</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">while</span>
<span style="color: #008080;">if</span> <span style="color: #7060A8;">mpz_cmp_si</span><span style="color: #0000FF;">(</span><span style="color: #000000;">factor</span><span style="color: #0000FF;">,</span><span style="color: #000000;">0</span><span style="color: #0000FF;">)!=</span><span style="color: #000000;">0</span> <span style="color: #008080;">then</span> <span style="color: #008080;">exit</span> <span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #000000;">k</span> <span style="color: #0000FF;">-=</span> <span style="color: #000000;">1</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">while</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #7060A8;">mpz_fdiv_qr</span><span style="color: #0000FF;">(</span><span style="color: #000000;">y</span><span style="color: #0000FF;">,</span><span style="color: #000000;">r</span><span style="color: #0000FF;">,</span><span style="color: #000000;">best</span><span style="color: #0000FF;">,</span><span style="color: #000000;">factor</span><span style="color: #0000FF;">)</span>
<span style="color: #7060A8;">assert</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">mpz_cmp_si</span><span style="color: #0000FF;">(</span><span style="color: #000000;">r</span><span style="color: #0000FF;">,</span><span style="color: #000000;">0</span><span style="color: #0000FF;">)=</span><span style="color: #000000;">0</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">return</span> <span style="color: #0000FF;">{</span><span style="color: #000000;">best</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">factor</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">y</span><span style="color: #0000FF;">}</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
<span style="color: #008080;">constant</span> <span style="color: #000000;">fmt</span> <span style="color: #0000FF;">=</span> <span style="color: #008000;">"Largest palindromic product of two %d-digit integers: %s = %s x %s (%s)\n"</span>
<span style="color: #008080;">for</span> <span style="color: #000000;">n</span><span style="color: #0000FF;">=</span><span style="color: #000000;">2</span> <span style="color: #008080;">to</span> <span style="color: #000000;">12</span> <span style="color: #008080;">do</span>
<span style="color: #004080;">atom</span> <span style="color: #000000;">t1</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">time</span><span style="color: #0000FF;">()</span>
<span style="color: #004080;">mpz</span> <span style="color: #0000FF;">{</span><span style="color: #000000;">p</span><span style="color: #0000FF;">,</span><span style="color: #000000;">x</span><span style="color: #0000FF;">,</span><span style="color: #000000;">y</span><span style="color: #0000FF;">}</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">pal2</span><span style="color: #0000FF;">(</span><span style="color: #000000;">n</span><span style="color: #0000FF;">)</span>
<span style="color: #004080;">string</span> <span style="color: #000000;">sp</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">mpz_get_str</span><span style="color: #0000FF;">(</span><span style="color: #000000;">p</span><span style="color: #0000FF;">),</span>
<span style="color: #000000;">sx</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">mpz_get_str</span><span style="color: #0000FF;">(</span><span style="color: #000000;">x</span><span style="color: #0000FF;">),</span>
<span style="color: #000000;">sy</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">mpz_get_str</span><span style="color: #0000FF;">(</span><span style="color: #000000;">y</span><span style="color: #0000FF;">),</span>
<span style="color: #000000;">e</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">elapsed</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">time</span><span style="color: #0000FF;">()-</span><span style="color: #000000;">t1</span><span style="color: #0000FF;">)</span>
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #000000;">fmt</span><span style="color: #0000FF;">,{</span><span style="color: #000000;">n</span><span style="color: #0000FF;">,</span><span style="color: #000000;">sp</span><span style="color: #0000FF;">,</span><span style="color: #000000;">sx</span><span style="color: #0000FF;">,</span><span style="color: #000000;">sy</span><span style="color: #0000FF;">,</span><span style="color: #000000;">e</span><span style="color: #0000FF;">})</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<!--</syntaxhighlight>-->
{{out}}
<pre>
Largest palindromic product of two 2-digit integers: 9009 = 99 x 91 (0s)
Largest palindromic product of two 3-digit integers: 906609 = 913 x 993 (0s)
Largest palindromic product of two 4-digit integers: 99000099 = 9999 x 9901 (0s)
Largest palindromic product of two 5-digit integers: 9966006699 = 99979 x 99681 (0s)
Largest palindromic product of two 6-digit integers: 999000000999 = 999999 x 999001 (0s)
Largest palindromic product of two 7-digit integers: 99956644665999 = 9997647 x 9998017 (0.0s)
Largest palindromic product of two 8-digit integers: 9999000000009999 = 99999999 x 99990001 (0s)
Largest palindromic product of two 9-digit integers: 999900665566009999 = 999920317 x 999980347 (0.8s)
Largest palindromic product of two 10-digit integers: 99999000000000099999 = 9999999999 x 9999900001 (0s)
Largest palindromic product of two 11-digit integers: 9999994020000204999999 = 99999996349 x 99999943851 (0.1s)
Largest palindromic product of two 12-digit integers: 999999000000000000999999 = 999999999999 x 999999000001 (0s)
</pre>
After that it starts to struggle a bit:
<pre>
Largest palindromic product of two 13-digit integers: 99999963342000024336999999 = 9999996340851 x 9999999993349 (40.4s)
Largest palindromic product of two 14-digit integers: 9999999000000000000009999999 = 99999999999999 x 99999990000001 (0s)
Largest palindromic product of two 15-digit integers: 999999974180040040081479999999 = 999999998341069 x 999999975838971 (1 minute and 12s)
Largest palindromic product of two 16-digit integers: 99999999000000000000000099999999 = 9999999999999999 x 9999999900000001 (0s)
</pre>
 
=={{header|Python}}==
Original author credit to user peijunz at Leetcode.
<syntaxhighlight lang="python">""" taken from https://leetcode.com/problems/largest-palindrome-product/discuss/150954/Fast-algorithm-by-constrains-on-tail-digits """
 
T=[set([(0, 0)])]
 
def double(it):
for a, b in it:
yield a, b
yield b, a
 
def tails(n):
'''Construct pair of n-digit numbers that their product ends with 99...9 pattern'''
if len(T)<=n:
l = set()
for i in range(10):
for j in range(i, 10):
I = i*10**(n-1)
J = j*10**(n-1)
it = tails(n-1)
if I!=J: it = double(it)
for t1, t2 in it:
if ((I+t1)*(J+t2)+1)%10**n == 0:
l.add((I+t1, J+t2))
T.append(l)
return T[n]
 
def largestPalindrome(n):
""" find largest palindrome that is a product of two n-digit numbers """
m, tail = 0, n // 2
head = n - tail
up = 10**head
for L in range(1, 9*10**(head-1)+1):
# Consider small shell (up-L)^2 < (up-i)*(up-j) <= (up-L)^2, 1<=i<=L<=j
m = 0
sol = None
for i in range(1, L + 1):
lo = max(i, int(up - (up - L + 1)**2 / (up - i)) + 1)
hi = int(up - (up - L)**2 / (up - i))
for j in range(lo, hi + 1):
I = (up-i) * 10**tail
J = (up-j) * 10**tail
it = tails(tail)
if I!=J: it = double(it)
for t1, t2 in it:
val = (I + t1)*(J + t2)
s = str(val)
if s == s[::-1] and val>m:
sol = (I + t1, J + t2)
m = val
 
if m:
print("{:2d}\t{:4d}".format(n, m % 1337), sol, sol[0] * sol[1])
return m % 1337
return 0
 
if __name__ == "__main__":
for k in range(1, 14):
largestPalindrome(k)
</syntaxhighlight>{{out}}
<pre>
1 9 (9, 1) 9
2 987 (91, 99) 9009
3 123 (993, 913) 906609
4 597 (9901, 9999) 99000099
5 677 (99979, 99681) 9966006699
6 1218 (999001, 999999) 999000000999
7 877 (9998017, 9997647) 99956644665999
8 475 (99990001, 99999999) 9999000000009999
9 1226 (999980347, 999920317) 999900665566009999
10 875 (9999986701, 9999996699) 99999834000043899999
11 108 (99999943851, 99999996349) 9999994020000204999999
12 378 (999999000001, 999999999999) 999999000000000000999999
13 1097 (9999999993349, 9999996340851) 99999963342000024336999999
</pre>
 
=={{header|Quackery}}==
 
The largest product of two 3 digit numbers is 999*999 = 998001.
The smallest product of two 3 digit numbers is 100*100 = 10000.
Therefore we need only consider 6 and 5 digit palindromic numbers.
 
Considering 6 digit palindromic numbers:
 
The largest is 999999.
The smallest is 100001.
These can be costructed from the numbers 100 to 999.
Therefore there are 899 6 digit palindromic numbers.
 
The same applies to 5 digit palindromic numbers:
The largest is 99999.
The smallest is 10001.
These can be costructed from the numbers 100 to 999.
Therefore there are 899 5 digit palindromic numbers.
 
'''Method:'''
 
* Construct the 6 digit palindromic numbers in reverse numerical order.
* Test each one to see if it is divisible by a 3 digit number with a 3 digit result, starting with 999.
* If it is, the solution has been found.
* If no solution found, consider 5 digit palindromes.
 
A six digit solution was found, and as it was found virtually instantaneously I did not feel that any optimisations were necessary.
 
I went on to find the largest five digit soultion, even though the task did not call for it, as it was a trivial exercise.
 
<syntaxhighlight lang="Quackery"> [ [] swap
[ 10 /mod
rot join swap
dup 0 = until ]
drop ] is ->digits ( n --> [ )
 
[ behead swap
witheach
[ swap 10 * + ] ] is ->number ( [ --> n )
 
[ ->digits
dup reverse join
->number ] is evenpal ( n --> n )
 
[ ->digits
dup reverse
behead drop join
->number ] is oddpal ( n --> n )
 
[ 2dup mod 0 != iff
[ 2drop false ]
done
/ 100 1000 within ] is solution ( n n --> b )
 
false
899 times
[ i 100 + evenpal
899 times
[ dup i 100 +
solution if
[ dip not
conclude ] ]
over iff
[ nip conclude ]
else drop ]
dup iff
[ say "Six digit solution found: " echo ]
else
[ drop say "No six digit solution found." ]
cr
false
899 times
[ i 100 + oddpal
899 times
[ dup i 100 +
solution if
[ dip not
conclude ] ]
over iff
[ nip conclude ]
else drop ]
dup iff
[ say "Five digit solution found: " echo ]
else
[ drop say "No five digit solution found." ]
</syntaxhighlight>
 
{{out}}
 
<pre>Six digit solution found: 906609
Five digit solution found: 99899
</pre>
 
=={{header|Raku}}==
 
<syntaxhighlight lang="raku" perl6line>use Inline::Perl5;
my $p5 = Inline::Perl5.new();
$p5.use: 'ntheory';
Line 451 ⟶ 1,323:
}
$p
}</langsyntaxhighlight>
<pre>Largest palindromic product of two 2-digit integers: 91 × 99 = 9009
Largest palindromic product of two 3-digit integers: 913 × 993 = 906609
Line 465 ⟶ 1,337:
 
=={{header|Ring}}==
<langsyntaxhighlight lang="ring">? "working..."
 
prod = 1
Line 513 ⟶ 1,385:
ok
end
return true</langsyntaxhighlight>
{{out}}
<pre>working...
Line 519 ⟶ 1,391:
Found in 6 iterations
done...</pre>
 
=={{header|RPL}}==
≪ "" OVER SIZE 1 '''FOR''' j
OVER j DUP SUB +
-1 '''STEP''' NIP
≫ '<span style="color:blue">REVSTR</span>' STO
≪ 1 CF
'''DO'''
1 -
DUP →STR DUP <span style="color:blue">REVSTR</span> + STR→
DUP DIVIS SORT
1 OVER SIZE '''FOR''' j
DUP j GET
DUP XPON 2
'''CASE'''
DUP2 < '''THEN''' 3 DROPN '''END'''
> '''THEN''' DROP DUP SIZE 'j' STO '''END'''
PICK3 SWAP /
'''IF''' XPON 2 == '''THEN''' 1 SF '''END'''
'''END'''
'''NEXT''' DROP2
'''UNTIL''' 1 FS? '''END'''
→STR DUP <span style="color:blue">REVSTR</span> + STR→
≫ '<span style="color:blue">P004</span>' STO
 
1000 <span style="color:blue">P004</span>
{{out}}
<pre>
1: 906609
</pre>
 
=={{header|Sidef}}==
<syntaxhighlight lang="ruby">func largest_palindrome_product (n) {
 
for k in ((10**n - 1) `downto` 10**(n-1)) {
var t = Num("#{k}#{Str(k).flip}")
 
t.divisors.each {|d|
if ((d.len == n) && ((t/d).len == n)) {
return (d, t/d)
}
}
}
}
 
for n in (2..9) {
var (a,b) = largest_palindrome_product(n)
say "Largest palindromic product of two #{n}-digit integers: #{a} * #{b} = #{a*b}"
}</syntaxhighlight>
{{out}}
<pre>
Largest palindromic product of two 2-digit integers: 91 * 99 = 9009
Largest palindromic product of two 3-digit integers: 913 * 993 = 906609
Largest palindromic product of two 4-digit integers: 9901 * 9999 = 99000099
Largest palindromic product of two 5-digit integers: 99681 * 99979 = 9966006699
Largest palindromic product of two 6-digit integers: 999001 * 999999 = 999000000999
Largest palindromic product of two 7-digit integers: 9997647 * 9998017 = 99956644665999
Largest palindromic product of two 8-digit integers: 99990001 * 99999999 = 9999000000009999
Largest palindromic product of two 9-digit integers: 999920317 * 999980347 = 999900665566009999
</pre>
 
=={{header|Wren}}==
The approach here is to manufacture palindromic numbers of length 2n in decreasing order and then see if they're products of two n-digit numbers.
<langsyntaxhighlight ecmascriptlang="wren">var reverse = Fn.new { |n|
var r = 0
while (n > 0) {
Line 557 ⟶ 1,490:
if (nextN) break
}
}</langsyntaxhighlight>
 
{{out}}
Line 570 ⟶ 1,503:
 
=={{header|XPL0}}==
<langsyntaxhighlight XPL0lang="xpl0">func Rev(A); \Reverse digits
int A, B;
[B:= 0;
Line 588 ⟶ 1,521:
];
IntOut(0, Max);
]</langsyntaxhighlight>
 
{{out}}
2,041

edits