Rare numbers: Difference between revisions

imported>Sassela
(Add Racket solution)
 
(5 intermediate revisions by 2 users not shown)
Line 3,894:
 
=== not optimized ===
It could look something like the following (ignoring whatever optimizations the other examples are using), if it was fast enough. I did not have the time/processor to test finding the first 5. The .israre() function appears to return the right answer, tested with individual numbers.
 
<syntaxhighlight lang="langur">
{{works with|langur|0.8.11}}
<syntaxhighlight lang="langur">val .perfectsquare = ffn isIntegern: .(n ^/ 2) div 1
 
val .israre = ffn(.n) {
val .r = reverse(.n)
if .n == .r: return false
val .sum = .n + .r
val .diff = .n - .r
.diff > 0 and .perfectsquare(.sum) and .perfectsquare(.diff)
}
 
val .findfirst = ffn(.maxmx) {
for[=[]] .i = 0; len(_for) < mx; .i += 1 {
if .israre(.i) {
_for ~= [.i]
if len(_for) == .max: break
}
}
}
 
val findandprint = impure fn(mx) {
# if you have the time...
for[cnt=0] i = 0; cnt < mx ; i += 1 {
writeln "the first 5 rare numbers: ", .findfirst(5)</syntaxhighlight>
if israre(i) {
writeln "\n rare ", i, " "
cnt += 1
}
}
}
 
# if you have the time...
With 0.8.11, the built-in reverse() function will flip the digits of a number. Without this, you could write your own function to do so as follows (if not passed any negative numbers).
writeln "the first 5 rare numbers: ", .findfirst(5)</syntaxhighlight>
 
</syntaxhighlight>
<syntaxhighlight lang="langur">val .reverse = f toNumber join reverse split .n</syntaxhighlight>
 
=={{header|Lua}}==
Line 6,512 ⟶ 6,517:
===Traditional===
About 9.5 minutes to find the first 25 rare numbers.
<syntaxhighlight lang="ecmascriptwren">import "./sort" for Sort
import "./fmt" for Fmt
 
class Term {
Line 6,786 ⟶ 6,791:
===Turbo===
Ruffles the feathers a little with a time 5 times quicker than the 'traditional' version.
<syntaxhighlight lang="ecmascriptwren">import "./sort" for Sort
import "./fmt" for Fmt
import "./date" for Date
 
class Z2 {
1,007

edits