Rebol3 Code Examplex
Jacobsthal numbers
Generate the Jacobsthal sequence.
Rebol [
title: "Rosetta code: Jacobsthal numbers"
file: %Jacobsthal_numbers.r3
url: https://rosettacode.org/wiki/Jacobsthal_numbers
note: "Based on Red language solution"
]
jacobsthal: func [
"Computes the nth Jacobsthal number via the formula"
n [number!]
][
2 ** n - (-1 ** n) / 3
]
lucas: func [
"Computes the nth Lucas number."
n [number!]
][
2 ** n + (-1 ** n)
]
oblong: func [
"Computes the product of Jacobsthal numbers for n and n+1"
n [number!]
][
multiply jacobsthal n jacobsthal n + 1
]
if unset? :prime? [
;; When native prime? function is not available...
prime?: function [
"Returns true if the input is a prime number"
n [number!] "An integer to check for primality"
][
if 2 = n [return true]
if any [n <= 1 even? n] [return false]
limit: square-root n
candidate: 3
while [candidate < limit][
if n % candidate = 0 [return false]
candidate: candidate + 2
]
true
]
]
show: function [n fn][
cols: 12
repeat i n [
prin [pad to integer! fn subtract i 1 cols]
if i % 5 = 0 [prin newline]
]
prin newline
]
print "First 30 Jacobsthal numbers:"
show 30 :jacobsthal
print "First 30 Jacobsthal-Lucas numbers:"
show 30 :lucas
print "First 20 Jacobsthal oblong numbers:"
show 20 :oblong
print "First 10 Jacobsthal primes:"
primes: n: 0
while [primes < 10][
if prime? jacob: to integer! jacobsthal n [
print jacob
primes: primes + 1
]
n: n + 1
]Output:
First 30 Jacobsthal numbers:
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
First 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
First 20 Jacobsthal oblong numbers:
0 1 3 15 55
231 903 3655 14535 58311
232903 932295 3727815 14913991 59650503
238612935 954429895 3817763271 15270965703 61084037575
First 10 Jacobsthal primes:
3
5
11
43
683
2731
43691
174763
2796203
715827883