Largest palindrome product: Difference between revisions
Content added Content deleted
SqrtNegInf (talk | contribs) 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 |
|||
prod = 1 |
|||
bestProd = 0 |
|||
⚫ | |||
// maximum 3 digit number |
|||
max = 999 |
|||
// both factors must be >100 for a 6 digit product |
|||
⚫ | |||
// one factor must be divisible by 11 |
|||
limitEnd = 11 * floor(max / 11) |
|||
⚫ | |||
iters = 0 |
|||
// loop from hi to low to find the best result in the fewest steps |
|||
⚫ | |||
for n = limitEnd to limitStart step -11 |
|||
// with n falling, the lower limit of m can rise with |
|||
⚫ | |||
// the best-found-so-far second number. Doing this |
|||
if prodNew > prodOld and palindrome(string(prodNew)) |
|||
// lowers the iteration count by a lot. |
|||
⚫ | |||
for m = max to second step -1 |
|||
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 |
|||
⚫ | |||
⚫ | |||
bestProd = prod |
|||
ok |
ok |
||
next |
next |
||
next |
next |
||
put "The largest palindrome is: " |
|||
? "" + bestProd + " = " + first + " * " + second |
|||
? "Found in " + iters + " iterations" |
|||
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... |
||
⚫ | |||
working... |
|||
Found in 6 iterations |
|||
⚫ | |||
⚫ | |||
913 * 993 = 906609 |
|||
⚫ | |||
</pre> |
|||
=={{header|Wren}}== |
=={{header|Wren}}== |