Largest palindrome product: Difference between revisions
Content added Content deleted
(→{{header|XPL0}}: faster version (226 vs. 99 ms on Pi4)) |
(julia example) |
||
Line 72: | Line 72: | ||
Largest palindromic product of two 8-digit integers: 99999999 x 99990001 = 9999000000009999 |
Largest palindromic product of two 8-digit integers: 99999999 x 99990001 = 9999000000009999 |
||
Largest palindromic product of two 9-digit integers: 999980347 x 999920317 = 999900665566009999 |
Largest palindromic product of two 9-digit integers: 999980347 x 999920317 = 999900665566009999 |
||
</pre> |
|||
=={{header|Julia}}== |
|||
<lang julia>using Primes |
|||
function twoprodpal(factorlength) |
|||
maxpal = Int128(10)^(2 * factorlength) - 1 |
|||
dig = digits(maxpal) |
|||
halfnum = dig[1:length(dig)÷2] |
|||
while any(halfnum .!= 0) |
|||
prodnum = evalpoly(Int128(10), [reverse(halfnum); halfnum]) |
|||
facs = twofac(factorlength, prodnum) |
|||
if !isempty(facs) |
|||
println("For factor length $factorlength, $(facs[1]) * $(facs[2]) = $prodnum") |
|||
break |
|||
end |
|||
halfnum = digits(evalpoly(Int128(10), halfnum) - 1) |
|||
end |
|||
end |
|||
function twofac(faclength, prodnum) |
|||
f = [one(prodnum)] |
|||
for (p, e) in factor(prodnum) |
|||
f = reduce(vcat, [f * p^j for j in 1:e], init=f) |
|||
end |
|||
possiblefacs = filter(x -> length(string(x)) == faclength, f) |
|||
for i in possiblefacs |
|||
j = prodnum ÷ i |
|||
j ∈ possiblefacs && return sort([i, j]) |
|||
end |
|||
return typeof(prodnum)[] |
|||
end |
|||
@Threads.threads for i in 2:12 |
|||
twoprodpal(i) |
|||
end |
|||
</lang>{{out}} |
|||
<pre> |
|||
For factor length 2, 91 * 99 = 9009 |
|||
For factor length 3, 913 * 993 = 906609 |
|||
For factor length 4, 9901 * 9999 = 99000099 |
|||
For factor length 5, 99681 * 99979 = 9966006699 |
|||
For factor length 6, 999001 * 999999 = 999000000999 |
|||
For factor length 7, 9997647 * 9998017 = 99956644665999 |
|||
For factor length 8, 99990001 * 99999999 = 9999000000009999 |
|||
For factor length 9, 999920317 * 999980347 = 999900665566009999 |
|||
For factor length 10, 9999986701 * 9999996699 = 99999834000043899999 |
|||
For factor length 11, 99999943851 * 99999996349 = 9999994020000204999999 |
|||
For factor length 12, 999999000001 * 999999999999 = 999999000000000000999999 |
|||
</pre> |
</pre> |
||