Rare numbers: Difference between revisions
→{{header|langur}}
(Added Lua) |
Langurmonkey (talk | contribs) |
||
(5 intermediate revisions by 3 users not shown) | |||
Line 3,896:
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">val .perfectsquare = f isInteger .n ^/ 2
val .israre =
val .r = reverse(.n)
if .n == .r: return false
Line 3,907 ⟶ 3,906:
}
val .findfirst =
for[=[]] .i = 0; len(_for) < .max; .i += 1 {
if .israre(.i) {
_for ~= [.i]
if len(_for) == .max: break▼
}
}
Line 3,918 ⟶ 3,916:
# if you have the time...
writeln "the first 5 rare numbers: ", .findfirst(5)</syntaxhighlight>
=={{header|Lua}}==
Line 4,880 ⟶ 4,874:
621770
281089082</pre>
=={{header|Racket}}==
===naive===
<syntaxhighlight lang="racket" line>; 20231024 Racket programming naive solution
#lang racket
(require control)
(require text-block/text)
(define (is-palindrome n)
(define (digit-list n)
(if (zero? n)
'()
(cons (remainder n 10) (digit-list (quotient n 10)))))
(define (reverse-list lst)
(if (null? lst)
'()
(append (reverse-list (cdr lst)) (list (car lst)))))
(define digits (digit-list n))
(equal? digits (reverse-list digits)))
(define (perfect-square? n)
(if (rational? (sqrt n))
(= n (expt (floor (sqrt n)) 2))
false))
(define (reverse-number n)
(string->number (string-reverse (number->string n))))
(define (find-rare-numbers count)
(define rare-numbers '())
(define i 1)
(define (is-rare? n)
(and (not (is-palindrome n))
(let* ((r (reverse-number n))
(diff (- n r)))
(and (perfect-square? sum)
(perfect-square? diff)))))
(define start-time (current-inexact-milliseconds))
(while (< (length rare-numbers) count)
(cond [(is-rare? i)
(displayln (format "Number: ~a | Elapsed time: ~a ms" i (round (- (current-inexact-milliseconds) start-time))))
(set! rare-numbers (cons i rare-numbers))])
(set! i (+ i 1)))
(reverse rare-numbers))
(displayln "The first 5 rare numbers are:")
(for-each (λ (x) (display x) (display "\n")) (find-rare-numbers 5))
</syntaxhighlight>
=={{header|Raku}}==
Line 6,457 ⟶ 6,506:
===Traditional===
About 9.5 minutes to find the first 25 rare numbers.
<syntaxhighlight lang="
import "./fmt" for Fmt
class Term {
Line 6,731 ⟶ 6,780:
===Turbo===
Ruffles the feathers a little with a time 5 times quicker than the 'traditional' version.
<syntaxhighlight lang="
import "./fmt" for Fmt
import "./date" for Date
class Z2 {
|