Largest palindrome product: Difference between revisions

No edit summary
Line 707:
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}}==
<lang Mathematica>palindromeQ[n_] :=
Block[{digits = IntegerDigits@n}, digits == Reverse[digits]]
nextPair[n_] :=
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}]</lang>
 
{{out}}<pre>
factors largest palindrome
{99,91} 9009
{913,993} 906609
{9999,9901} 99000099
{99979,99681} 9966006699
{999999,999001} 999000000999
{9997647,9998017} 99956644665999
</pre>
 
Anonymous user