Largest palindrome product: Difference between revisions

Content added Content deleted
m (→‎{{header|Perl}}: 'reverse' suffices)
m (→‎{{header|Ring}}: removed library dependence, improved performance by checking hi to low and terminating the inner loop once it's obvious the result won't be improved)
Line 138: Line 138:


=={{header|Ring}}==
=={{header|Ring}}==
<lang ring>
<lang ring>? "working..."
load "stdlib.ring"
see "working..." + nl


prodOld = 0
prod = 1
bestProd = 0
limitStart = 100
// maximum 3 digit number
limitEnd = 999
max = 999
// both factors must be >100 for a 6 digit product
limitStart = 101
// one factor must be divisible by 11
limitEnd = 11 * floor(max / 11)
second = limitStart
iters = 0


// loop from hi to low to find the best result in the fewest steps
for n = limitStart to limitEnd
for m = limitStart to limitEnd
for n = limitEnd to limitStart step -11
// with n falling, the lower limit of m can rise with
prodNew = n*m
// the best-found-so-far second number. Doing this
if prodNew > prodOld and palindrome(string(prodNew))
// lowers the iteration count by a lot.
prodOld = prodNew
first = n
for m = max to second step -1
second = m
prod = n * m
if isPal(prod)
iters++
// exit when the product stops increasing
if bestProd > prod
exit
ok
// maintain the best-found-so-far result
first = n
second = m
bestProd = prod
ok
ok
next
next
next
next


see "The largest palindrome is:" + nl
put "The largest palindrome is: "
see "" + first + " * " + second + " = " + prodOld + nl
? "" + bestProd + " = " + first + " * " + second
? "Found in " + iters + " iterations"
see "done..." + nl
put "done..."
</lang>

func isPal n
x = string(n)
l = len(x) + 1
i = 0
while i < l
if x[i++] != x[l--]
return false
ok
end
return true</lang>
{{out}}
{{out}}
<pre>
<pre>working...
The largest palindrome is: 906609 = 913 * 993
working...
Found in 6 iterations
The largest palindrome is:
done...</pre>
913 * 993 = 906609
done...
</pre>


=={{header|Wren}}==
=={{header|Wren}}==