Jacobsthal numbers: Difference between revisions
Content added Content deleted
m (→{{header|Haskell}}: (pruned one redundant $)) |
(→{{header|Haskell}}: Added a variant defined in terms of unfoldr) |
||
Line 829: | Line 829: | ||
[3,5,11,43,683,2731,43691,174763,2796203,715827883] |
[3,5,11,43,683,2731,43691,174763,2796203,715827883] |
||
</pre> |
</pre> |
||
or, defined in terms of unfoldr: |
|||
<lang haskell>import Data.List (intercalate, transpose, uncons, unfoldr) |
|||
import Data.List.Split (chunksOf) |
|||
import Data.Numbers.Primes (isPrime) |
|||
import Text.Printf (printf) |
|||
-------------------- JACOBSTHAL NUMBERS ------------------ |
|||
jacobsthal = jacobsthalish [0, 1] |
|||
jacobsthalish :: [Integer] -> [Integer] |
|||
jacobsthalish = unfoldr go |
|||
where |
|||
go xs = |
|||
let Just (a, t@(b : _)) = uncons xs |
|||
in Just (a, t <> [2 * a + b]) |
|||
--------------------------- TEST ------------------------- |
|||
main :: IO () |
|||
main = |
|||
mapM_ |
|||
(putStrLn . format) |
|||
[ ( "terms of the Jacobsthal sequence", |
|||
30, |
|||
jacobsthal |
|||
), |
|||
( "Jacobsthal-Lucas numbers", |
|||
30, |
|||
jacobsthalish [2, 1] |
|||
), |
|||
( "Jacobsthal oblong numbers", |
|||
20, |
|||
zipWith (*) jacobsthal (tail jacobsthal) |
|||
), |
|||
( "Jacobsthal primes", |
|||
10, |
|||
filter isPrime jacobsthal |
|||
) |
|||
] |
|||
format :: (String, Int, [Integer]) -> String |
|||
format (k, n, xs) = |
|||
show n <> (' ' : k) <> ":\n" |
|||
<> table |
|||
" " |
|||
(chunksOf 5 $ show <$> take n xs) |
|||
table :: String -> [[String]] -> String |
|||
table gap rows = |
|||
let ws = maximum . fmap length <$> transpose rows |
|||
pw = printf . flip intercalate ["%", "s"] . show |
|||
in unlines $ intercalate gap . zipWith pw ws <$> rows</lang> |
|||
{{Out}} |
|||
<pre>30 terms of the Jacobsthal sequence: |
|||
0 1 1 3 5 |
|||
11 21 43 85 171 |
|||
341 683 1365 2731 5461 |
|||
10923 21845 43691 87381 174763 |
|||
349525 699051 1398101 2796203 5592405 |
|||
11184811 22369621 44739243 89478485 178956971 |
|||
30 Jacobsthal-Lucas numbers: |
|||
2 1 5 7 17 |
|||
31 65 127 257 511 |
|||
1025 2047 4097 8191 16385 |
|||
32767 65537 131071 262145 524287 |
|||
1048577 2097151 4194305 8388607 16777217 |
|||
33554431 67108865 134217727 268435457 536870911 |
|||
20 Jacobsthal oblong numbers: |
|||
0 1 3 15 55 |
|||
231 903 3655 14535 58311 |
|||
232903 932295 3727815 14913991 59650503 |
|||
238612935 954429895 3817763271 15270965703 61084037575 |
|||
10 Jacobsthal primes: |
|||
3 5 11 43 683 |
|||
2731 43691 174763 2796203 715827883</pre> |
|||
=={{header|J}}== |
=={{header|J}}== |