RosettaCodeData/Task/Jacobsthal-numbers/Fennel/jacobsthal-numbers.fennel
2025-08-11 18:05:26 -07:00

64 lines
2.7 KiB
Fennel
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

(do ;;; find some Jacobsthal and related Numbers
(local (max-jacobsthal ; highest Jacobsthal number we will find
max-oblong ; highest Jacobsthal oblong number we will find
max-j-prime ; number of Jacobsthal primes we will find
) (values 29 20 10))
(local (j ; will hold Jacobsthal numbers
jl ; will hold Jacobsthal-Lucas numbers
jo ; will hold Jacobsthal oblong numbers
) (values [] [] []))
; calculate the Jacobsthal Numbers and related numbers
; Jacobsthal : J0 = 0, J1 = 1, Jn = Jn-1 + 2 × Jn-2
; Jacobsthal-Lucas: JL0 = 2, JL1 = 1, JLn = JLn-1 + 2 × JLn-2
; Jacobsthal oblong: JOn = Jn x Jn-1
; Lua arrays (and hence Fennel arrays) can be indexed from 0 but this uses indexing from 1,
; to follow the Agena and Pluto samples, so J0 is in j[ 1 ], JL0 is in jl[ 1 ], etc.
; but JO1 is in jo[ 1 ], however
(tset j 1 0) (tset j 2 1) (tset jl 1 2) (tset jl 2 1) (tset jo 1 0)
(for [n 2 max-jacobsthal]
(local (n+1 n-1) (values (+ n 1) (- n 1)))
(tset j n+1 (+ (. j n) (* 2 (. j n-1))))
(tset jl n+1 (+ (. jl n) (* 2 (. jl n-1))))
)
(for [n 1 max-oblong]
(tset jo n (* (. j (+ n 1)) (. j n)))
)
(fn is-prime [n]
(var result (or (= n 2) (and (> n 1) (= 1 (band n 1)))))
(when result
(var k 3)
(local max-k (math.floor (math.sqrt n)))
(while (and result (<= k max-k))
(set (result k) (values (not= 0 (% n k)) (+ k 2)))
)
)
result
)
(fn show-numbers [legend numbers]
(var nCount 0)
(io.write (string.format "First %d %s\n" (length numbers) legend))
(for [n 1 (length numbers)]
(io.write (string.format " %11d" (. numbers n)))
(set nCount (+ nCount 1))
(when (= 0 (% nCount 5)) (print))
)
)
; show the various numbers numbers
(show-numbers "Jacobsthal Numbers:" j )
(show-numbers "Jacobsthal-Lucas Numbers:" jl )
(show-numbers "Jacobsthal oblong Numbers:" jo )
; find some prime Jacobsthal numbers
(io.write (string.format "First %d Jacobstal primes:\n n Jn\n" max-j-prime))
(var (jn1 jn2 pCount n) (values (. j 2) (. j 1) 0 2))
(while (< pCount max-j-prime)
(local jn (+ jn1 (* 2 jn2)))
(set (jn2 jn1) (values jn1 jn))
(when (is-prime jn)
(set pCount (+ pCount 1))
(io.write (string.format "%4d: %d\n" n jn))
)
(set n (+ n 1))
)
)