Initial data commit
This commit is contained in:
parent
72d218235f
commit
f23f22d71c
199087 changed files with 3378941 additions and 0 deletions
2
Task/Jacobsthal-numbers/00-META.yaml
Normal file
2
Task/Jacobsthal-numbers/00-META.yaml
Normal file
|
|
@ -0,0 +1,2 @@
|
|||
---
|
||||
from: http://rosettacode.org/wiki/Jacobsthal_numbers
|
||||
49
Task/Jacobsthal-numbers/00-TASK.txt
Normal file
49
Task/Jacobsthal-numbers/00-TASK.txt
Normal file
|
|
@ -0,0 +1,49 @@
|
|||
'''Jacobsthal numbers''' are an integer sequence related to Fibonacci numbers. Similar to Fibonacci, where each term is the sum of the previous two terms, each term is the sum of the previous, plus twice the one before that. Traditionally the sequence starts with the given terms 0, 1.
|
||||
|
||||
<span style="font-size:125%;font-weight:bold;">
|
||||
J<sub>0</sub> = 0
|
||||
J<sub>1</sub> = 1
|
||||
J<sub>n</sub> = J<sub>n-1</sub> + 2 × J<sub>n-2</sub>
|
||||
</span>
|
||||
|
||||
Terms may be calculated directly using one of several possible formulas:
|
||||
<span style="font-size:125%;font-weight:bold;">
|
||||
J<sub>n</sub> = ( 2<sup>n</sup> - (-1)<sup>n</sup> ) / 3
|
||||
</span>
|
||||
|
||||
|
||||
'''Jacobsthal-Lucas numbers''' are very similar. They have the same recurrence relationship, the only difference is an initial starting value '''J<sub>0</sub> = 2''' rather than '''J<sub>0</sub> = 0'''.
|
||||
|
||||
Terms may be calculated directly using one of several possible formulas:
|
||||
<span style="font-size:125%;font-weight:bold;">
|
||||
JL<sub>n</sub> = 2<sup>n</sup> + (-1)<sup>n</sup>
|
||||
</span>
|
||||
|
||||
'''Jacobsthal oblong numbers''' is the sequence obtained from multiplying each '''Jacobsthal number''' '''J<sub>n</sub>''' by its direct successor '''J<sub>n+1</sub>'''.
|
||||
|
||||
|
||||
'''Jacobsthal primes''' are '''Jacobsthal numbers''' that are prime.
|
||||
|
||||
|
||||
|
||||
;Task
|
||||
* Find and display the first 30 '''Jacobsthal numbers'''
|
||||
* Find and display the first 30 '''Jacobsthal-Lucas numbers'''
|
||||
* Find and display the first 20 '''Jacobsthal oblong numbers'''
|
||||
* Find and display at least the first 10 '''Jacobsthal primes'''
|
||||
|
||||
|
||||
|
||||
;See also
|
||||
;* [[wp:Jacobsthal_number|Wikipedia: Jacobsthal number]]
|
||||
;* [https://www.numbersaplenty.com/set/Jacobsthal_number Numbers Aplenty - Jacobsthal number]
|
||||
;* [[oeis:A001045|OEIS:A001045 - Jacobsthal sequence (or Jacobsthal numbers)]]
|
||||
;* [[oeis:A014551|OEIS:A014551 - Jacobsthal-Lucas numbers.]]
|
||||
;* [[oeis:A084175|OEIS:A084175 - Jacobsthal oblong numbers]]
|
||||
;* [[oeis:A049883|OEIS:A049883 - Primes in the Jacobsthal sequence]]
|
||||
;* [[Fibonacci sequence|Related task: Fibonacci sequence]]
|
||||
;* [[Leonardo numbers|Related task: Leonardo numbers]]
|
||||
|
||||
|
||||
|
||||
|
||||
34
Task/Jacobsthal-numbers/11l/jacobsthal-numbers.11l
Normal file
34
Task/Jacobsthal-numbers/11l/jacobsthal-numbers.11l
Normal file
|
|
@ -0,0 +1,34 @@
|
|||
F isPrime(n)
|
||||
L(i) 2 .. Int(n ^ 0.5)
|
||||
I n % i == 0
|
||||
R 0B
|
||||
R 1B
|
||||
|
||||
F odd(n)
|
||||
R n [&] 1 != 0
|
||||
|
||||
F jacobsthal(n)
|
||||
R floori((pow(2.0, n) + odd(n)) / 3)
|
||||
|
||||
F jacobsthal_lucas(n)
|
||||
R Int(pow(2, n) + pow(-1, n))
|
||||
|
||||
F jacobsthal_oblong(n)
|
||||
R Int64(jacobsthal(n)) * jacobsthal(n + 1)
|
||||
|
||||
print(‘First 30 Jacobsthal numbers:’)
|
||||
L(j) 0..29
|
||||
print(jacobsthal(j), end' ‘ ’)
|
||||
|
||||
print("\n\nFirst 30 Jacobsthal-Lucas numbers: ")
|
||||
L(j) 0..29
|
||||
print(jacobsthal_lucas(j), end' "\t")
|
||||
|
||||
print("\n\nFirst 20 Jacobsthal oblong numbers: ")
|
||||
L(j) 0..19
|
||||
print(jacobsthal_oblong(j), end' ‘ ’)
|
||||
|
||||
print("\n\nFirst 10 Jacobsthal primes: ")
|
||||
L(j) 3..32
|
||||
I isPrime(jacobsthal(j))
|
||||
print(jacobsthal(j))
|
||||
51
Task/Jacobsthal-numbers/ALGOL-68/jacobsthal-numbers.alg
Normal file
51
Task/Jacobsthal-numbers/ALGOL-68/jacobsthal-numbers.alg
Normal file
|
|
@ -0,0 +1,51 @@
|
|||
BEGIN # find some Jacobsthal and related Numbers #
|
||||
INT max jacobsthal = 29; # highest Jacobsthal number we will find #
|
||||
INT max oblong = 20; # highest Jacobsthal oblong number we will find #
|
||||
INT max j prime = 20; # number of Jacobsthal prinmes we will find #
|
||||
PR precision 200 PR # set the precision of LONG LONG INT #
|
||||
PR read "primes.incl.a68" PR # include prime utilities #
|
||||
[ 0 : max jacobsthal ]LONG INT j; # will hold Jacobsthal numbers #
|
||||
[ 0 : max jacobsthal ]LONG INT jl; # will hold Jacobsthal-Lucas numbers #
|
||||
[ 1 : max oblong ]LONG INT jo; # will hold Jacobsthal oblong numbers #
|
||||
# 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 #
|
||||
j[ 0 ] := 0; j[ 1 ] := 1; jl[ 0 ] := 2; jl[ 1 ] := 1; jo[ 1 ] := 0;
|
||||
FOR n FROM 2 TO UPB j DO
|
||||
j[ n ] := j[ n - 1 ] + ( 2 * j[ n - 2 ] );
|
||||
jl[ n ] := jl[ n - 1 ] + ( 2 * jl[ n - 2 ] )
|
||||
OD;
|
||||
FOR n TO UPB jo DO
|
||||
jo[ n ] := j[ n ] * j[ n - 1 ]
|
||||
OD;
|
||||
# prints an array of numbers with the specified legend #
|
||||
PROC show numbers = ( STRING legend, []LONG INT numbers )VOID:
|
||||
BEGIN
|
||||
INT n count := 0;
|
||||
print( ( "First ", whole( ( UPB numbers - LWB numbers ) + 1, 0 ), " ", legend, newline ) );
|
||||
FOR n FROM LWB numbers TO UPB numbers DO
|
||||
print( ( " ", whole( numbers[ n ], -11 ) ) );
|
||||
IF ( n count +:= 1 ) MOD 5 = 0 THEN print( ( newline ) ) FI
|
||||
OD
|
||||
END # show numbers # ;
|
||||
# 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 #
|
||||
LONG LONG INT jn1 := j[ 1 ], jn2 := j[ 0 ];
|
||||
INT p count := 0;
|
||||
print( ( "First ", whole( max j prime, 0 ), " Jacobstal primes:", newline ) );
|
||||
print( ( " n Jn", newline ) );
|
||||
FOR n FROM 2 WHILE p count < max j prime DO
|
||||
LONG LONG INT jn = jn1 + ( 2 * jn2 );
|
||||
jn2 := jn1;
|
||||
jn1 := jn;
|
||||
IF is probably prime( jn ) THEN
|
||||
# have a probably prime Jacobsthal number #
|
||||
p count +:= 1;
|
||||
print( ( whole( n, -4 ), ": ", whole( jn, 0 ), newline ) )
|
||||
FI
|
||||
OD
|
||||
END
|
||||
|
|
@ -0,0 +1,133 @@
|
|||
on jacobsthalNumbers(variant, n)
|
||||
-- variant: text containing "Lucas", "oblong", or "prime" — or none of these.
|
||||
-- n: length of output sequence required.
|
||||
|
||||
-- The two Jacobsthal numbers preceding the current 'j'. Initially the first two in the sequence.
|
||||
set {anteprev, prev} to {0, 1}
|
||||
-- Default plug-in script. Its handler simply appends the current 'j' to the output.
|
||||
script o
|
||||
property output : {anteprev, prev}
|
||||
on append(dummy, j)
|
||||
set end of output to j
|
||||
end append
|
||||
end script
|
||||
|
||||
-- If a variant sequence is specified, change the first value or substitute
|
||||
-- a script whose handler decides the values to append to the output.
|
||||
ignoring case
|
||||
if (variant contains "Lucas") then
|
||||
set anteprev to 2
|
||||
set o's output's first item to anteprev
|
||||
else if (variant contains "oblong") then
|
||||
script
|
||||
property output : {0}
|
||||
on append(prev, j)
|
||||
set end of output to prev * j
|
||||
end append
|
||||
end script
|
||||
set o to result
|
||||
else if (variant contains "prime") then
|
||||
script
|
||||
property output : {}
|
||||
on append(dummy, j)
|
||||
if (isPrime(j)) then set end of output to j
|
||||
end append
|
||||
end script
|
||||
set o to result
|
||||
end if
|
||||
end ignoring
|
||||
|
||||
-- Work through the Jacobsthal process until the required output length is obtained.
|
||||
repeat until ((count o's output) = n)
|
||||
set j to anteprev + anteprev + prev
|
||||
tell o to append(prev, j)
|
||||
set anteprev to prev
|
||||
set prev to j
|
||||
end repeat
|
||||
|
||||
return o's output
|
||||
end jacobsthalNumbers
|
||||
|
||||
on isPrime(n)
|
||||
if (n < 3) then return (n is 2)
|
||||
if (n mod 2 is 0) then return false
|
||||
repeat with i from 3 to (n ^ 0.5) div 1 by 2
|
||||
if (n mod i is 0) then return false
|
||||
end repeat
|
||||
return true
|
||||
end isPrime
|
||||
|
||||
-- Task and presentation of results!:
|
||||
on intToText(n)
|
||||
set txt to ""
|
||||
repeat until (n < 100000000)
|
||||
set txt to text 2 thru 9 of (100000000 + (n mod 100000000) div 1 as text) & txt
|
||||
set n to n div 100000000
|
||||
end repeat
|
||||
return (n as integer as text) & txt
|
||||
end intToText
|
||||
|
||||
on chopList(theList, sublistLen)
|
||||
script o
|
||||
property lst : theList
|
||||
property output : {}
|
||||
end script
|
||||
|
||||
set listLen to (count o's lst)
|
||||
repeat with i from 1 to listLen by sublistLen
|
||||
set j to i + sublistLen - 1
|
||||
if (j > listLen) then set j to listLen
|
||||
set end of o's output to items i thru j of o's lst
|
||||
end repeat
|
||||
return o's output
|
||||
end chopList
|
||||
|
||||
on matrixToText(matrix, w)
|
||||
script o
|
||||
property matrix : missing value
|
||||
property row : missing value
|
||||
end script
|
||||
|
||||
set o's matrix to matrix
|
||||
set padding to " "
|
||||
repeat with r from 1 to (count o's matrix)
|
||||
set o's row to o's matrix's item r
|
||||
repeat with i from 1 to (count o's row)
|
||||
set o's row's item i to text -w thru end of (padding & o's row's item i)
|
||||
end repeat
|
||||
set o's matrix's item r to join(o's row, "")
|
||||
end repeat
|
||||
|
||||
return join(o's matrix, linefeed)
|
||||
end matrixToText
|
||||
|
||||
on join(lst, delim)
|
||||
set astid to AppleScript's text item delimiters
|
||||
set AppleScript's text item delimiters to delim
|
||||
set txt to lst as text
|
||||
set AppleScript's text item delimiters to astid
|
||||
return txt
|
||||
end join
|
||||
|
||||
on task()
|
||||
set output to {"First 30 Jacobsthal Numbers:", "First 30 Jacobsthal-Lucas Numbers:", ¬
|
||||
"First 20 Jacobsthal oblong Numbers:", "First 11 Jacobsthal Primes:"}
|
||||
set results to {jacobsthalNumbers("", 30), jacobsthalNumbers("Lucas", 30), ¬
|
||||
jacobsthalNumbers("oblong", 20), jacobsthalNumbers("prime", 11)}
|
||||
repeat with i from 1 to 4
|
||||
set thisSequence to item i of results
|
||||
repeat with j in thisSequence
|
||||
set j's contents to intToText(j)
|
||||
end repeat
|
||||
if (i < 4) then
|
||||
set theLines to chopList(thisSequence, 10)
|
||||
else
|
||||
set theLines to chopList(thisSequence, 6)
|
||||
end if
|
||||
set item i of output to item i of output & linefeed & matrixToText(theLines, (count end of thisSequence) + 1)
|
||||
end repeat
|
||||
|
||||
return join(output, linefeed & linefeed)
|
||||
end task
|
||||
|
||||
task()
|
||||
|
|
@ -0,0 +1,17 @@
|
|||
"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 11 Jacobsthal Primes:
|
||||
3 5 11 43 683 2731
|
||||
43691 174763 2796203 715827883 2932031007403"
|
||||
|
|
@ -0,0 +1,436 @@
|
|||
-------------------- JACOBSTHAL NUMBERS ------------------
|
||||
|
||||
-- e.g. take(10, jacobsthal())
|
||||
|
||||
-- jacobsthal :: [Int]
|
||||
on jacobsthal()
|
||||
-- The terms of OEIS:A001045 as a non-finite sequence.
|
||||
jacobsthalish(0, 1)
|
||||
end jacobsthal
|
||||
|
||||
|
||||
-- jacobsthal :: (Int, Int) -> [Int]
|
||||
on jacobsthalish(x, y)
|
||||
-- An infinite sequence of the terms of the
|
||||
-- Jacobsthal-type series which begins with x and y.
|
||||
script go
|
||||
on |λ|(ab)
|
||||
set {a, b} to ab
|
||||
|
||||
{a, {b, (2 * a) + b}}
|
||||
end |λ|
|
||||
end script
|
||||
|
||||
unfoldr(go, {x, y})
|
||||
end jacobsthalish
|
||||
|
||||
|
||||
-------------------------- TESTS -------------------------
|
||||
on run
|
||||
unlines(map(fShow, {¬
|
||||
{"terms of the Jacobsthal sequence", ¬
|
||||
30, jacobsthal()}, ¬
|
||||
{"Jacobsthal-Lucas numbers", ¬
|
||||
30, jacobsthalish(2, 1)}, ¬
|
||||
{"Jacobsthal oblong numbers", ¬
|
||||
20, zipWith(my mul, jacobsthal(), drop(1, jacobsthal()))}, ¬
|
||||
{"primes in the Jacobsthal sequence", ¬
|
||||
10, filter(isPrime, jacobsthal())}}))
|
||||
end run
|
||||
|
||||
|
||||
------------------------ FORMATTING ----------------------
|
||||
on fShow(test)
|
||||
set {k, n, xs} to test
|
||||
|
||||
str(n) & " first " & k & ":" & linefeed & ¬
|
||||
table(5, map(my str, take(n, xs))) & linefeed
|
||||
end fShow
|
||||
|
||||
|
||||
-- justifyRight :: Int -> Char -> String -> String
|
||||
on justifyRight(n, cFiller)
|
||||
script go
|
||||
on |λ|(s)
|
||||
if n > length of s then
|
||||
text -n thru -1 of ((replicate(n, cFiller) as text) & s)
|
||||
else
|
||||
s
|
||||
end if
|
||||
end |λ|
|
||||
end script
|
||||
end justifyRight
|
||||
|
||||
|
||||
-- Egyptian multiplication - progressively doubling a list, appending
|
||||
-- stages of doubling to an accumulator where needed for binary
|
||||
-- assembly of a target length
|
||||
-- replicate :: Int -> String -> String
|
||||
on replicate(n, s)
|
||||
-- Egyptian multiplication - progressively doubling a list,
|
||||
-- appending stages of doubling to an accumulator where needed
|
||||
-- for binary assembly of a target length
|
||||
script p
|
||||
on |λ|({n})
|
||||
n ≤ 1
|
||||
end |λ|
|
||||
end script
|
||||
|
||||
script f
|
||||
on |λ|({n, dbl, out})
|
||||
if (n mod 2) > 0 then
|
||||
set d to out & dbl
|
||||
else
|
||||
set d to out
|
||||
end if
|
||||
{n div 2, dbl & dbl, d}
|
||||
end |λ|
|
||||
end script
|
||||
|
||||
set xs to |until|(p, f, {n, s, ""})
|
||||
item 2 of xs & item 3 of xs
|
||||
end replicate
|
||||
|
||||
|
||||
-- table :: Int -> [String] -> String
|
||||
on table(n, xs)
|
||||
-- A list of strings formatted as
|
||||
-- right-justified rows of n columns.
|
||||
set w to length of last item of xs
|
||||
unlines(map(my unwords, ¬
|
||||
chunksOf(n, map(justifyRight(w, space), xs))))
|
||||
end table
|
||||
|
||||
|
||||
-- unlines :: [String] -> String
|
||||
on unlines(xs)
|
||||
-- A single string formed by the intercalation
|
||||
-- of a list of strings with the newline character.
|
||||
set {dlm, my text item delimiters} to ¬
|
||||
{my text item delimiters, linefeed}
|
||||
set s to xs as text
|
||||
set my text item delimiters to dlm
|
||||
s
|
||||
end unlines
|
||||
|
||||
|
||||
-- until :: (a -> Bool) -> (a -> a) -> a -> a
|
||||
on |until|(p, f, x)
|
||||
set v to x
|
||||
set mp to mReturn(p)
|
||||
set mf to mReturn(f)
|
||||
repeat until mp's |λ|(v)
|
||||
set v to mf's |λ|(v)
|
||||
end repeat
|
||||
v
|
||||
end |until|
|
||||
|
||||
|
||||
-- unwords :: [String] -> String
|
||||
on unwords(xs)
|
||||
set {dlm, my text item delimiters} to ¬
|
||||
{my text item delimiters, space}
|
||||
set s to xs as text
|
||||
set my text item delimiters to dlm
|
||||
return s
|
||||
end unwords
|
||||
|
||||
|
||||
------------------------- GENERIC ------------------------
|
||||
|
||||
-- Just :: a -> Maybe a
|
||||
on Just(x)
|
||||
-- Constructor for an inhabited Maybe (option type) value.
|
||||
-- Wrapper containing the result of a computation.
|
||||
{type:"Maybe", Nothing:false, Just:x}
|
||||
end Just
|
||||
|
||||
|
||||
-- Nothing :: Maybe a
|
||||
on Nothing()
|
||||
-- Constructor for an empty Maybe (option type) value.
|
||||
-- Empty wrapper returned where a computation is not possible.
|
||||
{type:"Maybe", Nothing:true}
|
||||
end Nothing
|
||||
|
||||
|
||||
-- abs :: Num -> Num
|
||||
on abs(x)
|
||||
-- Absolute value.
|
||||
if 0 > x then
|
||||
-x
|
||||
else
|
||||
x
|
||||
end if
|
||||
end abs
|
||||
|
||||
|
||||
-- any :: (a -> Bool) -> [a] -> Bool
|
||||
on any(p, xs)
|
||||
-- Applied to a predicate and a list,
|
||||
-- |any| returns true if at least one element of the
|
||||
-- list satisfies the predicate.
|
||||
tell mReturn(p)
|
||||
set lng to length of xs
|
||||
repeat with i from 1 to lng
|
||||
if |λ|(item i of xs) then return true
|
||||
end repeat
|
||||
false
|
||||
end tell
|
||||
end any
|
||||
|
||||
|
||||
-- chunksOf :: Int -> [a] -> [[a]]
|
||||
on chunksOf(k, xs)
|
||||
script
|
||||
on go(ys)
|
||||
set ab to splitAt(k, ys)
|
||||
set a to item 1 of ab
|
||||
if {} ≠ a then
|
||||
{a} & go(item 2 of ab)
|
||||
else
|
||||
a
|
||||
end if
|
||||
end go
|
||||
end script
|
||||
result's go(xs)
|
||||
end chunksOf
|
||||
|
||||
|
||||
-- drop :: Int -> [a] -> [a]
|
||||
-- drop :: Int -> String -> String
|
||||
on drop(n, xs)
|
||||
take(n, xs) -- consumed
|
||||
xs
|
||||
end drop
|
||||
|
||||
|
||||
-- enumFromThenTo :: Int -> Int -> Int -> [Int]
|
||||
on enumFromThenTo(x1, x2, y)
|
||||
set xs to {}
|
||||
set gap to x2 - x1
|
||||
set d to max(1, abs(gap)) * (signum(gap))
|
||||
repeat with i from x1 to y by d
|
||||
set end of xs to i
|
||||
end repeat
|
||||
return xs
|
||||
end enumFromThenTo
|
||||
|
||||
|
||||
-- filter :: (a -> Bool) -> Gen [a] -> Gen [a]
|
||||
on filter(p, gen)
|
||||
-- Non-finite stream of values which are
|
||||
-- drawn from gen, and satisfy p
|
||||
script
|
||||
property mp : mReturn(p)'s |λ|
|
||||
on |λ|()
|
||||
set v to gen's |λ|()
|
||||
repeat until mp(v)
|
||||
set v to gen's |λ|()
|
||||
end repeat
|
||||
return v
|
||||
end |λ|
|
||||
end script
|
||||
end filter
|
||||
|
||||
|
||||
-- isPrime :: Int -> Bool
|
||||
on isPrime(n)
|
||||
-- True if n is prime
|
||||
|
||||
if {2, 3} contains n then return true
|
||||
|
||||
if 2 > n or 0 = (n mod 2) then return false
|
||||
|
||||
if 9 > n then return true
|
||||
|
||||
if 0 = (n mod 3) then return false
|
||||
|
||||
script p
|
||||
on |λ|(x)
|
||||
0 = n mod x or 0 = n mod (2 + x)
|
||||
end |λ|
|
||||
end script
|
||||
|
||||
not any(p, enumFromThenTo(5, 11, 1 + (n ^ 0.5)))
|
||||
end isPrime
|
||||
|
||||
|
||||
-- length :: [a] -> Int
|
||||
on |length|(xs)
|
||||
set c to class of xs
|
||||
if list is c or string is c then
|
||||
length of xs
|
||||
else
|
||||
(2 ^ 29 - 1) -- (maxInt - simple proxy for non-finite)
|
||||
end if
|
||||
end |length|
|
||||
|
||||
|
||||
-- map :: (a -> b) -> [a] -> [b]
|
||||
on map(f, xs)
|
||||
-- The list obtained by applying f
|
||||
-- to each element of xs.
|
||||
tell mReturn(f)
|
||||
set lng to length of xs
|
||||
set lst to {}
|
||||
repeat with i from 1 to lng
|
||||
set end of lst to |λ|(item i of xs, i, xs)
|
||||
end repeat
|
||||
return lst
|
||||
end tell
|
||||
end map
|
||||
|
||||
|
||||
-- max :: Ord a => a -> a -> a
|
||||
on max(x, y)
|
||||
if x > y then
|
||||
x
|
||||
else
|
||||
y
|
||||
end if
|
||||
end max
|
||||
|
||||
|
||||
-- mReturn :: First-class m => (a -> b) -> m (a -> b)
|
||||
on mReturn(f)
|
||||
-- 2nd class handler function lifted into 1st class script wrapper.
|
||||
if script is class of f then
|
||||
f
|
||||
else
|
||||
script
|
||||
property |λ| : f
|
||||
end script
|
||||
end if
|
||||
end mReturn
|
||||
|
||||
|
||||
-- mul (*) :: Num a => a -> a -> a
|
||||
on mul(a, b)
|
||||
a * b
|
||||
end mul
|
||||
|
||||
|
||||
-- signum :: Num -> Num
|
||||
on signum(x)
|
||||
if x < 0 then
|
||||
-1
|
||||
else if x = 0 then
|
||||
0
|
||||
else
|
||||
1
|
||||
end if
|
||||
end signum
|
||||
|
||||
|
||||
-- splitAt :: Int -> [a] -> ([a], [a])
|
||||
on splitAt(n, xs)
|
||||
if n > 0 and n < length of xs then
|
||||
if class of xs is text then
|
||||
{items 1 thru n of xs as text, ¬
|
||||
items (n + 1) thru -1 of xs as text}
|
||||
else
|
||||
{items 1 thru n of xs, items (n + 1) thru -1 of xs}
|
||||
end if
|
||||
else
|
||||
if n < 1 then
|
||||
{{}, xs}
|
||||
else
|
||||
{xs, {}}
|
||||
end if
|
||||
end if
|
||||
end splitAt
|
||||
|
||||
|
||||
-- str :: a -> String
|
||||
on str(x)
|
||||
x as string
|
||||
end str
|
||||
|
||||
|
||||
-- take :: Int -> [a] -> [a]
|
||||
-- take :: Int -> String -> String
|
||||
on take(n, xs)
|
||||
set ys to {}
|
||||
repeat with i from 1 to n
|
||||
set v to |λ|() of xs
|
||||
if missing value is v then
|
||||
return ys
|
||||
else
|
||||
set end of ys to v
|
||||
end if
|
||||
end repeat
|
||||
return ys
|
||||
end take
|
||||
|
||||
|
||||
-- uncons :: [a] -> Maybe (a, [a])
|
||||
on uncons(xs)
|
||||
set lng to |length|(xs)
|
||||
if 0 = lng then
|
||||
Nothing()
|
||||
else
|
||||
if (2 ^ 29 - 1) as integer > lng then
|
||||
if class of xs is string then
|
||||
set cs to text items of xs
|
||||
Just({item 1 of cs, rest of cs})
|
||||
else
|
||||
Just({item 1 of xs, rest of xs})
|
||||
end if
|
||||
else
|
||||
set nxt to take(1, xs)
|
||||
if {} is nxt then
|
||||
Nothing()
|
||||
else
|
||||
Just({item 1 of nxt, xs})
|
||||
end if
|
||||
end if
|
||||
end if
|
||||
end uncons
|
||||
|
||||
|
||||
-- unfoldr :: (b -> Maybe (a, b)) -> b -> [a]
|
||||
on unfoldr(f, v)
|
||||
-- A lazy (generator) list unfolded from a seed value
|
||||
-- by repeated application of f to a value until no
|
||||
-- residue remains. Dual to fold/reduce.
|
||||
-- f returns either nothing (missing value)
|
||||
-- or just (value, residue).
|
||||
script
|
||||
property valueResidue : {v, v}
|
||||
property g : mReturn(f)
|
||||
on |λ|()
|
||||
set valueResidue to g's |λ|(item 2 of (valueResidue))
|
||||
if missing value ≠ valueResidue then
|
||||
item 1 of (valueResidue)
|
||||
else
|
||||
missing value
|
||||
end if
|
||||
end |λ|
|
||||
end script
|
||||
end unfoldr
|
||||
|
||||
|
||||
-- zipWith :: (a -> b -> c) -> Gen [a] -> Gen [b] -> Gen [c]
|
||||
on zipWith(f, ga, gb)
|
||||
script
|
||||
property ma : missing value
|
||||
property mb : missing value
|
||||
property mf : mReturn(f)
|
||||
on |λ|()
|
||||
if missing value is ma then
|
||||
set ma to uncons(ga)
|
||||
set mb to uncons(gb)
|
||||
end if
|
||||
if Nothing of ma or Nothing of mb then
|
||||
missing value
|
||||
else
|
||||
set ta to Just of ma
|
||||
set tb to Just of mb
|
||||
set ma to uncons(item 2 of ta)
|
||||
set mb to uncons(item 2 of tb)
|
||||
|λ|(item 1 of ta, item 1 of tb) of mf
|
||||
end if
|
||||
end |λ|
|
||||
end script
|
||||
end zipWith
|
||||
28
Task/Jacobsthal-numbers/Arturo/jacobsthal-numbers.arturo
Normal file
28
Task/Jacobsthal-numbers/Arturo/jacobsthal-numbers.arturo
Normal file
|
|
@ -0,0 +1,28 @@
|
|||
J: function [n]-> ((2^n) - (neg 1)^n)/3
|
||||
JL: function [n]-> (2^n) + (neg 1)^n
|
||||
JO: function [n]-> (J n) * (J n+1)
|
||||
|
||||
printFirst: function [label, what, predicate, count][
|
||||
print ["First" count label++":"]
|
||||
result: new []
|
||||
i: 0
|
||||
while [count > size result][
|
||||
num: do ~"|what| i"
|
||||
if do predicate -> 'result ++ num
|
||||
i: i + 1
|
||||
]
|
||||
|
||||
(predicate=[true])? [
|
||||
loop split.every: 5 result 'row [
|
||||
print map to [:string] row 'item -> pad item 12
|
||||
]
|
||||
][
|
||||
loop result 'row -> print row
|
||||
]
|
||||
print ""
|
||||
]
|
||||
|
||||
printFirst "Jacobsthal numbers" 'J [true] 30
|
||||
printFirst "Jacobsthal-Lucas numbers" 'JL [true] 30
|
||||
printFirst "Jacobsthal oblong numbers" 'JO [true] 20
|
||||
printFirst "Jacobsthal primes" 'J [prime? num] 20
|
||||
35
Task/Jacobsthal-numbers/AutoHotkey/jacobsthal-numbers-1.ahk
Normal file
35
Task/Jacobsthal-numbers/AutoHotkey/jacobsthal-numbers-1.ahk
Normal file
|
|
@ -0,0 +1,35 @@
|
|||
Jacobsthal(n){
|
||||
return SubStr(" " Format("{:.0f}", (2**n - (-1)**n ) / 3), -8)
|
||||
}
|
||||
|
||||
Jacobsthal_Lucas(n){
|
||||
return SubStr(" " Format("{:.0f}", 2**n + (-1)**n), -8)
|
||||
}
|
||||
|
||||
prime_numbers(n) {
|
||||
if (n <= 3)
|
||||
return [n]
|
||||
ans := [], done := false
|
||||
while !done {
|
||||
if !Mod(n,2)
|
||||
ans.push(2), n /= 2
|
||||
else if !Mod(n,3)
|
||||
ans.push(3), n /= 3
|
||||
else if (n = 1)
|
||||
return ans
|
||||
else {
|
||||
sr := sqrt(n), done := true, i := 6
|
||||
while (i <= sr+6) {
|
||||
if !Mod(n, i-1) { ; is n divisible by i-1?
|
||||
ans.push(i-1), n /= i-1, done := false
|
||||
break
|
||||
}
|
||||
if !Mod(n, i+1) { ; is n divisible by i+1?
|
||||
ans.push(i+1), n /= i+1, done := false
|
||||
break
|
||||
}
|
||||
i += 6
|
||||
}}}
|
||||
ans.push(n)
|
||||
return ans
|
||||
}
|
||||
20
Task/Jacobsthal-numbers/AutoHotkey/jacobsthal-numbers-2.ahk
Normal file
20
Task/Jacobsthal-numbers/AutoHotkey/jacobsthal-numbers-2.ahk
Normal file
|
|
@ -0,0 +1,20 @@
|
|||
result := "First 30 Jacobsthal numbers:`n"
|
||||
loop 30
|
||||
result .= Jacobsthal(A_Index-1) (mod(A_Index, 5) ? " ":"`n")
|
||||
|
||||
result .= "`nFirst 30 Jacobsthal-Lucas numbers:`n"
|
||||
loop 30
|
||||
result .= Jacobsthal_Lucas(A_Index-1) (mod(A_Index, 5) ? " ":"`n")
|
||||
|
||||
result .= "`nFirst 20 Jacobsthal oblong numbers:`n"
|
||||
loop 20
|
||||
result .= SubStr(" " Jacobsthal(A_Index-1) * Jacobsthal(A_Index), -8) (mod(A_Index, 5) ? " ":"`n")
|
||||
|
||||
result .= "`nFirst 10 Jacobsthal primes:`n"
|
||||
c:=0
|
||||
while c < 10
|
||||
if (prime_numbers(x:=Jacobsthal(A_Index)).Count() = 1 && x > 1)
|
||||
result .= x (mod(++c, 5) ? " ":"`n")
|
||||
|
||||
MsgBox, 262144, , % result
|
||||
return
|
||||
48
Task/Jacobsthal-numbers/C++/jacobsthal-numbers.cpp
Normal file
48
Task/Jacobsthal-numbers/C++/jacobsthal-numbers.cpp
Normal file
|
|
@ -0,0 +1,48 @@
|
|||
#include <gmpxx.h>
|
||||
|
||||
#include <iomanip>
|
||||
#include <iostream>
|
||||
|
||||
using big_int = mpz_class;
|
||||
|
||||
bool is_probably_prime(const big_int& n) {
|
||||
return mpz_probab_prime_p(n.get_mpz_t(), 30) != 0;
|
||||
}
|
||||
|
||||
big_int jacobsthal_number(unsigned int n) {
|
||||
return ((big_int(1) << n) - (n % 2 == 0 ? 1 : -1)) / 3;
|
||||
}
|
||||
|
||||
big_int jacobsthal_lucas_number(unsigned int n) {
|
||||
return (big_int(1) << n) + (n % 2 == 0 ? 1 : -1);
|
||||
}
|
||||
|
||||
big_int jacobsthal_oblong_number(unsigned int n) {
|
||||
return jacobsthal_number(n) * jacobsthal_number(n + 1);
|
||||
}
|
||||
|
||||
int main() {
|
||||
std::cout << "First 30 Jacobsthal Numbers:\n";
|
||||
for (unsigned int n = 0; n < 30; ++n) {
|
||||
std::cout << std::setw(9) << jacobsthal_number(n)
|
||||
<< ((n + 1) % 5 == 0 ? '\n' : ' ');
|
||||
}
|
||||
std::cout << "\nFirst 30 Jacobsthal-Lucas Numbers:\n";
|
||||
for (unsigned int n = 0; n < 30; ++n) {
|
||||
std::cout << std::setw(9) << jacobsthal_lucas_number(n)
|
||||
<< ((n + 1) % 5 == 0 ? '\n' : ' ');
|
||||
}
|
||||
std::cout << "\nFirst 20 Jacobsthal oblong Numbers:\n";
|
||||
for (unsigned int n = 0; n < 20; ++n) {
|
||||
std::cout << std::setw(11) << jacobsthal_oblong_number(n)
|
||||
<< ((n + 1) % 5 == 0 ? '\n' : ' ');
|
||||
}
|
||||
std::cout << "\nFirst 20 Jacobsthal primes:\n";
|
||||
for (unsigned int n = 0, count = 0; count < 20; ++n) {
|
||||
auto jn = jacobsthal_number(n);
|
||||
if (is_probably_prime(jn)) {
|
||||
++count;
|
||||
std::cout << jn << '\n';
|
||||
}
|
||||
}
|
||||
}
|
||||
61
Task/Jacobsthal-numbers/C/jacobsthal-numbers.c
Normal file
61
Task/Jacobsthal-numbers/C/jacobsthal-numbers.c
Normal file
|
|
@ -0,0 +1,61 @@
|
|||
#include <stdio.h>
|
||||
#include <gmp.h>
|
||||
|
||||
void jacobsthal(mpz_t r, unsigned long n) {
|
||||
mpz_t s;
|
||||
mpz_init(s);
|
||||
mpz_set_ui(r, 1);
|
||||
mpz_mul_2exp(r, r, n);
|
||||
mpz_set_ui(s, 1);
|
||||
if (n % 2) mpz_neg(s, s);
|
||||
mpz_sub(r, r, s);
|
||||
mpz_div_ui(r, r, 3);
|
||||
}
|
||||
|
||||
void jacobsthal_lucas(mpz_t r, unsigned long n) {
|
||||
mpz_t a;
|
||||
mpz_init(a);
|
||||
mpz_set_ui(r, 1);
|
||||
mpz_mul_2exp(r, r, n);
|
||||
mpz_set_ui(a, 1);
|
||||
if (n % 2) mpz_neg(a, a);
|
||||
mpz_add(r, r, a);
|
||||
}
|
||||
|
||||
int main() {
|
||||
int i, count;
|
||||
mpz_t jac[30], j;
|
||||
printf("First 30 Jacobsthal numbers:\n");
|
||||
for (i = 0; i < 30; ++i) {
|
||||
mpz_init(jac[i]);
|
||||
jacobsthal(jac[i], i);
|
||||
gmp_printf("%9Zd ", jac[i]);
|
||||
if (!((i+1)%5)) printf("\n");
|
||||
}
|
||||
|
||||
printf("\nFirst 30 Jacobsthal-Lucas numbers:\n");
|
||||
mpz_init(j);
|
||||
for (i = 0; i < 30; ++i) {
|
||||
jacobsthal_lucas(j, i);
|
||||
gmp_printf("%9Zd ", j);
|
||||
if (!((i+1)%5)) printf("\n");
|
||||
}
|
||||
|
||||
printf("\nFirst 20 Jacobsthal oblong numbers:\n");
|
||||
for (i = 0; i < 20; ++i) {
|
||||
mpz_mul(j, jac[i], jac[i+1]);
|
||||
gmp_printf("%11Zd ", j);
|
||||
if (!((i+1)%5)) printf("\n");
|
||||
}
|
||||
|
||||
printf("\nFirst 20 Jacobsthal primes:\n");
|
||||
for (i = 0, count = 0; count < 20; ++i) {
|
||||
jacobsthal(j, i);
|
||||
if (mpz_probab_prime_p(j, 15) > 0) {
|
||||
gmp_printf("%Zd\n", j);
|
||||
++count;
|
||||
}
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
91
Task/Jacobsthal-numbers/Delphi/jacobsthal-numbers.delphi
Normal file
91
Task/Jacobsthal-numbers/Delphi/jacobsthal-numbers.delphi
Normal file
|
|
@ -0,0 +1,91 @@
|
|||
procedure GetJacobsthalNum(Lucas: boolean; Max: integer; var IA: TInt64DynArray);
|
||||
{Get Jacobsthal number sequence. If Lucas is true do Lucal variation}
|
||||
var I: integer;
|
||||
begin
|
||||
SetLength(IA,Max);
|
||||
{Lucas starts sequence with 2 instead of 0}
|
||||
if Lucas then IA[0]:=2 else IA[0]:=0;
|
||||
IA[1]:=1;
|
||||
{Calculate Nn = Nn-1 + 2 Nn-2}
|
||||
for I:=2 to Max-1 do
|
||||
IA[I]:=IA[I-1] + 2 * IA[I-2];
|
||||
end;
|
||||
|
||||
|
||||
procedure GetJacobsthalOblong(Max: integer; var IA: TInt64DynArray);
|
||||
{Jacobsthal Oblong numbers is Nn = Jn x Jn=1 where J = Jacobsthal numbers}
|
||||
var IA2: TInt64DynArray;
|
||||
var I: integer;
|
||||
begin
|
||||
GetJacobsthalNum(False,Max+1,IA2);
|
||||
SetLength(IA,Max);
|
||||
for I:=0 to High(IA2)-1 do
|
||||
begin
|
||||
IA[I]:=IA2[I] * IA2[I+1];
|
||||
end;
|
||||
end;
|
||||
|
||||
|
||||
procedure GetJacobsthalPrimes(Memo: TMemo);
|
||||
var I: integer;
|
||||
var Jacob,N1, N2: int64;
|
||||
|
||||
function GetNext: int64;
|
||||
{Nn = Nn-1 + 2 x Nn-2}
|
||||
begin
|
||||
Result:=N1 + 2 * N2;
|
||||
N2:=N1; N1:=Result;
|
||||
end;
|
||||
|
||||
begin
|
||||
N2:=0; N1:=1;
|
||||
for I:=1 to 10 do
|
||||
begin
|
||||
repeat Jacob:=GetNext;
|
||||
until IsPrime(Jacob);
|
||||
Memo.Lines.Add(IntToStr(I)+' - '+IntToStr(Jacob));
|
||||
end;
|
||||
end;
|
||||
|
||||
|
||||
|
||||
procedure ShowJacobsthalNumbers(Memo: TMemo);
|
||||
var I: integer;
|
||||
var IA: TInt64DynArray;
|
||||
var S: string;
|
||||
begin
|
||||
GetJacobsthalNum(False,30,IA);
|
||||
Memo.Lines.Add('First 30 Jacobsthal Numbers');
|
||||
S:='';
|
||||
for I:=0 to High(IA) do
|
||||
begin
|
||||
S:=S+Format('%12.0n',[IA[I]+0.0]);
|
||||
if (I mod 5)=4 then S:=S+CRLF;
|
||||
end;
|
||||
Memo.Lines.Add(S);
|
||||
|
||||
Memo.Lines.Add('');
|
||||
GetJacobsthalNum(True,30,IA);
|
||||
Memo.Lines.Add('First 30 Jacobsthal-Lucas Numbers');
|
||||
S:='';
|
||||
for I:=0 to High(IA) do
|
||||
begin
|
||||
S:=S+Format('%14.0n',[IA[I]+0.0]);
|
||||
if (I mod 4)=3 then S:=S+CRLF;
|
||||
end;
|
||||
Memo.Lines.Add(S);
|
||||
|
||||
Memo.Lines.Add('');
|
||||
GetJacobsthalOblong(20,IA);
|
||||
Memo.Lines.Add('First 20 Jacobsthal-Oblong Numbers');
|
||||
S:='';
|
||||
for I:=0 to High(IA) do
|
||||
begin
|
||||
S:=S+Format('%18.0n',[IA[I]+0.0]);
|
||||
if (I mod 3)=2 then S:=S+CRLF;
|
||||
end;
|
||||
Memo.Lines.Add(S);
|
||||
|
||||
Memo.Lines.Add('');
|
||||
GetJacobsthalPrimes(Memo);
|
||||
end;
|
||||
7
Task/Jacobsthal-numbers/F-Sharp/jacobsthal-numbers.fs
Normal file
7
Task/Jacobsthal-numbers/F-Sharp/jacobsthal-numbers.fs
Normal file
|
|
@ -0,0 +1,7 @@
|
|||
// Jacobsthal numbers: Nigel Galloway January 10th., 2023
|
||||
let J,JL=let fN g ()=Seq.unfold(fun(n,g)->Some(n,(g,g+2UL*n)))(g,1UL) in (fN 0UL,fN 2UL)
|
||||
printf "First 30 Jacobsthal are "; J()|>Seq.take 30|>Seq.iter(printf "%d "); printfn ""
|
||||
printf "First 30 Jacobsthal-Lucas are "; JL()|>Seq.take 30|>Seq.iter(printf "%d "); printfn ""
|
||||
printf "First 20 Jacobsthal Oblong are "; J()|>Seq.pairwise|>Seq.take 20|>Seq.iter(fun(n,g)->printf "%d " (n*g)); printfn ""
|
||||
let fN g= Open.Numeric.Primes.MillerRabin.IsPrime &g
|
||||
printf "First 10 Jacobsthal Primes are "; J()|>Seq.filter fN|>Seq.take 10|>Seq.iter(printf "%d "); printfn ""
|
||||
26
Task/Jacobsthal-numbers/Factor/jacobsthal-numbers.factor
Normal file
26
Task/Jacobsthal-numbers/Factor/jacobsthal-numbers.factor
Normal file
|
|
@ -0,0 +1,26 @@
|
|||
USING: grouping io kernel lists lists.lazy math math.functions
|
||||
math.primes prettyprint sequences ;
|
||||
|
||||
: 2^-1^ ( n -- 2^n -1^n ) dup 2^ -1 rot ^ ;
|
||||
: jacobsthal ( m -- n ) 2^-1^ - 3 / ;
|
||||
: jacobsthal-lucas ( m -- n ) 2^-1^ + ;
|
||||
: as-list ( quot -- list ) 0 lfrom swap lmap-lazy ; inline
|
||||
: jacobsthals ( -- list ) [ jacobsthal ] as-list ;
|
||||
: lucas-jacobthals ( -- list ) [ jacobsthal-lucas ] as-list ;
|
||||
: prime-jacobsthals ( -- list ) jacobsthals [ prime? ] lfilter ;
|
||||
: show ( n list -- ) ltake list>array 5 group simple-table. nl ;
|
||||
|
||||
: oblong ( -- list )
|
||||
jacobsthals dup cdr lzip [ product ] lmap-lazy ;
|
||||
|
||||
"First 30 Jacobsthal numbers:" print
|
||||
30 jacobsthals show
|
||||
|
||||
"First 30 Jacobsthal-Lucas numbers:" print
|
||||
30 lucas-jacobthals show
|
||||
|
||||
"First 20 Jacobsthal oblong numbers:" print
|
||||
20 oblong show
|
||||
|
||||
"First 20 Jacobsthal primes:" print
|
||||
20 prime-jacobsthals ltake [ . ] leach
|
||||
51
Task/Jacobsthal-numbers/FreeBASIC/jacobsthal-numbers.basic
Normal file
51
Task/Jacobsthal-numbers/FreeBASIC/jacobsthal-numbers.basic
Normal file
|
|
@ -0,0 +1,51 @@
|
|||
Function isPrime(n As Ulongint) As Boolean
|
||||
If n < 2 Then Return False
|
||||
If n Mod 2 = 0 Then Return false
|
||||
For i As Uinteger = 3 To Int(Sqr(n))+1 Step 2
|
||||
If n Mod i = 0 Then Return false
|
||||
Next i
|
||||
Return true
|
||||
End Function
|
||||
|
||||
Dim Shared As Uinteger n(1)
|
||||
Dim Shared As Uinteger i0 = 0, i1 = 1
|
||||
Dim Shared As Integer j, c, P = 1, Q = -2
|
||||
|
||||
Print "First 30 Jacobsthal numbers:"
|
||||
c = 0 : n(i0) = 0: n(i1) = 1
|
||||
For j = 0 To 29
|
||||
c += 1
|
||||
Print Using " #########"; n(i0);
|
||||
Print Iif (c Mod 5, "", !"\n");
|
||||
n(i0) = P * n(i1) - Q * n(i0)
|
||||
Swap i0, i1
|
||||
Next j
|
||||
|
||||
Print !"\n\nFirst 30 Jacobsthal-Lucas numbers: "
|
||||
c = 0 : n(i0) = 2: n(i1) = 1
|
||||
For j = 0 To 29
|
||||
c += 1
|
||||
Print Using " #########"; n(i0);
|
||||
Print Iif (c Mod 5, "", !"\n");
|
||||
n(i0) = P * n(i1) - Q * n(i0)
|
||||
Swap i0, i1
|
||||
Next j
|
||||
|
||||
Print !"\n\nFirst 20 Jacobsthal oblong numbers: "
|
||||
c = 0 : n(i0) = 0: n(i1) = 1
|
||||
For j = 0 To 19
|
||||
c += 1
|
||||
Print Using " ###########"; n(i0)*n(i1);
|
||||
Print Iif (c Mod 5, "", !"\n");
|
||||
n(i0) = P * n(i1) - Q * n(i0)
|
||||
Swap i0, i1
|
||||
Next j
|
||||
|
||||
Print !"\n\nFirst 10 Jacobsthal primes: "
|
||||
c = 0 : n(i0) = 0: n(i1) = 1
|
||||
Do
|
||||
If isPrime(n(i0)) Then c += 1 : Print n(i0)
|
||||
n(i0) = P * n(i1) - Q * n(i0)
|
||||
Swap i0, i1
|
||||
Loop Until c = 10
|
||||
Sleep
|
||||
82
Task/Jacobsthal-numbers/Gambas/jacobsthal-numbers.gambas
Normal file
82
Task/Jacobsthal-numbers/Gambas/jacobsthal-numbers.gambas
Normal file
|
|
@ -0,0 +1,82 @@
|
|||
Public n As New Long[2]
|
||||
|
||||
Public Sub Main()
|
||||
|
||||
Dim i0 As Integer = 0, i1 As Integer = 1
|
||||
Dim j As Integer, c As Integer, P As Integer = 1, Q As Integer = -2
|
||||
|
||||
Print "First 30 Jacobsthal numbers:"
|
||||
c = 0
|
||||
n[i0] = 0
|
||||
n[i1] = 1
|
||||
For j = 0 To 29
|
||||
c += 1
|
||||
Print Format$(n[i0], " #########");
|
||||
If (c Mod 5) Then
|
||||
Print "";
|
||||
Else
|
||||
Print Chr(10);
|
||||
End If
|
||||
n[i0] = P * n[i1] - Q * n[i0]
|
||||
Swap i0, i1
|
||||
Next
|
||||
|
||||
Print "\n\nFirst 30 Jacobsthal-Lucas numbers: "
|
||||
c = 0
|
||||
n[i0] = 2
|
||||
n[i1] = 1
|
||||
For j = 0 To 29
|
||||
c += 1
|
||||
Print Format$(n[i0], " #########");
|
||||
If (c Mod 5) Then
|
||||
Print "";
|
||||
Else
|
||||
Print Chr(10);
|
||||
End If
|
||||
n[i0] = P * n[i1] - Q * n[i0]
|
||||
Swap i0, i1
|
||||
Next
|
||||
|
||||
Print "\n\nFirst 20 Jacobsthal oblong numbers: "
|
||||
c = 0
|
||||
n[i0] = 0
|
||||
n[i1] = 1
|
||||
For j = 0 To 19
|
||||
c += 1
|
||||
Print Format$(n[i0] * n[i1], " ###########");
|
||||
If (c Mod 5) Then
|
||||
Print "";
|
||||
Else
|
||||
Print Chr(10);
|
||||
End If
|
||||
n[i0] = P * n[i1] - Q * n[i0]
|
||||
Swap i0, i1
|
||||
Next
|
||||
|
||||
Print "\n\nFirst 10 Jacobsthal primes: "
|
||||
c = 0
|
||||
n[i0] = 0
|
||||
n[i1] = 1
|
||||
Do
|
||||
If isPrime(n[i0]) Then
|
||||
c += 1
|
||||
Print n[i0]
|
||||
End If
|
||||
n[i0] = P * n[i1] - Q * n[i0]
|
||||
Swap i0, i1
|
||||
Loop Until c = 10
|
||||
|
||||
End
|
||||
|
||||
Public Sub isPrime(ValorEval As Long) As Boolean
|
||||
|
||||
If ValorEval < 2 Then Return False
|
||||
If ValorEval Mod 2 = 0 Then Return ValorEval = 2
|
||||
If ValorEval Mod 3 = 0 Then Return ValorEval = 3
|
||||
Dim d As Long = 5
|
||||
While d * d <= ValorEval
|
||||
If ValorEval Mod d = 0 Then Return False Else d += 2
|
||||
Wend
|
||||
Return True
|
||||
|
||||
End Function
|
||||
65
Task/Jacobsthal-numbers/Go/jacobsthal-numbers.go
Normal file
65
Task/Jacobsthal-numbers/Go/jacobsthal-numbers.go
Normal file
|
|
@ -0,0 +1,65 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"math/big"
|
||||
)
|
||||
|
||||
func jacobsthal(n uint) *big.Int {
|
||||
t := big.NewInt(1)
|
||||
t.Lsh(t, n)
|
||||
s := big.NewInt(1)
|
||||
if n%2 != 0 {
|
||||
s.Neg(s)
|
||||
}
|
||||
t.Sub(t, s)
|
||||
return t.Div(t, big.NewInt(3))
|
||||
}
|
||||
|
||||
func jacobsthalLucas(n uint) *big.Int {
|
||||
t := big.NewInt(1)
|
||||
t.Lsh(t, n)
|
||||
a := big.NewInt(1)
|
||||
if n%2 != 0 {
|
||||
a.Neg(a)
|
||||
}
|
||||
return t.Add(t, a)
|
||||
}
|
||||
|
||||
func main() {
|
||||
jac := make([]*big.Int, 30)
|
||||
fmt.Println("First 30 Jacobsthal numbers:")
|
||||
for i := uint(0); i < 30; i++ {
|
||||
jac[i] = jacobsthal(i)
|
||||
fmt.Printf("%9d ", jac[i])
|
||||
if (i+1)%5 == 0 {
|
||||
fmt.Println()
|
||||
}
|
||||
}
|
||||
|
||||
fmt.Println("\nFirst 30 Jacobsthal-Lucas numbers:")
|
||||
for i := uint(0); i < 30; i++ {
|
||||
fmt.Printf("%9d ", jacobsthalLucas(i))
|
||||
if (i+1)%5 == 0 {
|
||||
fmt.Println()
|
||||
}
|
||||
}
|
||||
|
||||
fmt.Println("\nFirst 20 Jacobsthal oblong numbers:")
|
||||
for i := uint(0); i < 20; i++ {
|
||||
t := big.NewInt(0)
|
||||
fmt.Printf("%11d ", t.Mul(jac[i], jac[i+1]))
|
||||
if (i+1)%5 == 0 {
|
||||
fmt.Println()
|
||||
}
|
||||
}
|
||||
|
||||
fmt.Println("\nFirst 20 Jacobsthal primes:")
|
||||
for n, count := uint(0), 0; count < 20; n++ {
|
||||
j := jacobsthal(n)
|
||||
if j.ProbablyPrime(10) {
|
||||
fmt.Println(j)
|
||||
count++
|
||||
}
|
||||
}
|
||||
}
|
||||
25
Task/Jacobsthal-numbers/Haskell/jacobsthal-numbers-1.hs
Normal file
25
Task/Jacobsthal-numbers/Haskell/jacobsthal-numbers-1.hs
Normal file
|
|
@ -0,0 +1,25 @@
|
|||
jacobsthal :: [Integer]
|
||||
jacobsthal = 0 : 1 : zipWith (\x y -> 2 * x + y) jacobsthal (tail jacobsthal)
|
||||
|
||||
jacobsthalLucas :: [Integer]
|
||||
jacobsthalLucas = 2 : 1 : zipWith (\x y -> 2 * x + y) jacobsthalLucas (tail jacobsthalLucas)
|
||||
|
||||
jacobsthalOblong :: [Integer]
|
||||
jacobsthalOblong = zipWith (*) jacobsthal (tail jacobsthal)
|
||||
|
||||
isPrime :: Integer -> Bool
|
||||
isPrime n = n > 1 && not (or [n `mod` i == 0 | i <- [2 .. floor (sqrt (fromInteger n))]])
|
||||
|
||||
main :: IO ()
|
||||
main = do
|
||||
putStrLn "First 30 Jacobsthal numbers:"
|
||||
print $ take 30 jacobsthal
|
||||
putStrLn ""
|
||||
putStrLn "First 30 Jacobsthal-Lucas numbers:"
|
||||
print $ take 30 jacobsthalLucas
|
||||
putStrLn ""
|
||||
putStrLn "First 20 Jacobsthal oblong numbers:"
|
||||
print $ take 20 jacobsthalOblong
|
||||
putStrLn ""
|
||||
putStrLn "First 10 Jacobsthal primes:"
|
||||
print $ take 10 $ filter isPrime jacobsthal
|
||||
50
Task/Jacobsthal-numbers/Haskell/jacobsthal-numbers-2.hs
Normal file
50
Task/Jacobsthal-numbers/Haskell/jacobsthal-numbers-2.hs
Normal file
|
|
@ -0,0 +1,50 @@
|
|||
import Data.List (intercalate, transpose, uncons, unfoldr)
|
||||
import Data.List.Split (chunksOf)
|
||||
import Data.Numbers.Primes (isPrime)
|
||||
import Text.Printf (printf)
|
||||
|
||||
-------------------- JACOBSTHAL NUMBERS ------------------
|
||||
|
||||
jacobsthal :: [Integer]
|
||||
jacobsthal = jacobsthalish (0, 1)
|
||||
|
||||
jacobsthalish :: (Integer, Integer) -> [Integer]
|
||||
jacobsthalish = unfoldr go
|
||||
where
|
||||
go (a, b) = Just (a, (b, 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
|
||||
2
Task/Jacobsthal-numbers/J/jacobsthal-numbers-1.j
Normal file
2
Task/Jacobsthal-numbers/J/jacobsthal-numbers-1.j
Normal file
|
|
@ -0,0 +1,2 @@
|
|||
ja=: 3 %~ 2x&^ - _1x&^ NB. Jacobsthal
|
||||
jl=: 2x&^ + _1x&^ NB.Jacobsthal-Lucas
|
||||
13
Task/Jacobsthal-numbers/J/jacobsthal-numbers-2.j
Normal file
13
Task/Jacobsthal-numbers/J/jacobsthal-numbers-2.j
Normal file
|
|
@ -0,0 +1,13 @@
|
|||
ja i.3 10
|
||||
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
|
||||
jl i.3 10
|
||||
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
|
||||
2 10$2 */\ ja i.21 NB. Jacobsthal oblong
|
||||
0 1 3 15 55 231 903 3655 14535 58311
|
||||
232903 932295 3727815 14913991 59650503 238612935 954429895 3817763271 15270965703 61084037575
|
||||
ja I.1 p:ja i.32 NB. first ten Jacobsthal primes
|
||||
3 5 11 43 683 2731 43691 174763 2796203 715827883
|
||||
72
Task/Jacobsthal-numbers/Java/jacobsthal-numbers.java
Normal file
72
Task/Jacobsthal-numbers/Java/jacobsthal-numbers.java
Normal file
|
|
@ -0,0 +1,72 @@
|
|||
import java.math.BigInteger;
|
||||
|
||||
public final class JacobsthalNumbers {
|
||||
|
||||
public static void main(String[] aArgs) {
|
||||
System.out.println("The first 30 Jacobsthal Numbers:");
|
||||
for ( int i = 0; i < 6; i++ ) {
|
||||
for ( int k = 0; k < 5; k++ ) {
|
||||
System.out.print(String.format("%15s", jacobsthalNumber(i * 5 + k)));
|
||||
}
|
||||
System.out.println();
|
||||
}
|
||||
System.out.println();
|
||||
|
||||
System.out.println("The first 30 Jacobsthal-Lucas Numbers:");
|
||||
for ( int i = 0; i < 6; i++ ) {
|
||||
for ( int k = 0; k < 5; k++ ) {
|
||||
System.out.print(String.format("%15s", jacobsthalLucasNumber(i * 5 + k)));
|
||||
}
|
||||
System.out.println();
|
||||
}
|
||||
System.out.println();
|
||||
|
||||
System.out.println("The first 20 Jacobsthal oblong Numbers:");
|
||||
for ( int i = 0; i < 4; i++ ) {
|
||||
for ( int k = 0; k < 5; k++ ) {
|
||||
System.out.print(String.format("%15s", jacobsthalOblongNumber(i * 5 + k)));
|
||||
}
|
||||
System.out.println();
|
||||
}
|
||||
System.out.println();
|
||||
|
||||
System.out.println("The first 10 Jacobsthal Primes:");
|
||||
for ( int i = 0; i < 10; i++ ) {
|
||||
System.out.println(jacobsthalPrimeNumber(i));
|
||||
}
|
||||
}
|
||||
|
||||
private static BigInteger jacobsthalNumber(int aIndex) {
|
||||
BigInteger value = BigInteger.valueOf(parityValue(aIndex));
|
||||
return BigInteger.ONE.shiftLeft(aIndex).subtract(value).divide(THREE);
|
||||
}
|
||||
|
||||
private static long jacobsthalLucasNumber(int aIndex) {
|
||||
return ( 1 << aIndex ) + parityValue(aIndex);
|
||||
}
|
||||
|
||||
private static long jacobsthalOblongNumber(int aIndex) {
|
||||
long nextJacobsthal = jacobsthalNumber(aIndex + 1).longValueExact();
|
||||
long result = currentJacobsthal * nextJacobsthal;
|
||||
currentJacobsthal = nextJacobsthal;
|
||||
return result;
|
||||
}
|
||||
|
||||
private static long jacobsthalPrimeNumber(int aIndex) {
|
||||
BigInteger candidate = jacobsthalNumber(latestIndex++);
|
||||
while ( ! candidate.isProbablePrime(CERTAINTY) ) {
|
||||
candidate = jacobsthalNumber(latestIndex++);
|
||||
}
|
||||
return candidate.longValueExact();
|
||||
}
|
||||
|
||||
private static int parityValue(int aIndex) {
|
||||
return ( aIndex & 1 ) == 0 ? +1 : -1;
|
||||
}
|
||||
|
||||
private static long currentJacobsthal = 0;
|
||||
private static int latestIndex = 0;
|
||||
|
||||
private static final BigInteger THREE = BigInteger.valueOf(3);
|
||||
private static final int CERTAINTY = 20;
|
||||
}
|
||||
17
Task/Jacobsthal-numbers/Jq/jacobsthal-numbers-1.jq
Normal file
17
Task/Jacobsthal-numbers/Jq/jacobsthal-numbers-1.jq
Normal file
|
|
@ -0,0 +1,17 @@
|
|||
# Split the input array into a stream of arrays
|
||||
def chunks(n):
|
||||
def c: .[0:n], (if length > n then .[n:]|c else empty end);
|
||||
c;
|
||||
|
||||
def lpad($len): tostring | ($len - length) as $l | (" " * $l)[:$l] + .;
|
||||
|
||||
# If $j is 0, then an error condition is raised;
|
||||
# otherwise, assuming infinite-precision integer arithmetic,
|
||||
# if the input and $j are integers, then the result will be a pair of integers.
|
||||
def divmod($j):
|
||||
. as $i
|
||||
| ($i % $j) as $mod
|
||||
| [($i - $mod) / $j, $mod] ;
|
||||
|
||||
# To take advantage of gojq's arbitrary-precision integer arithmetic:
|
||||
def power($b): . as $in | reduce range(0;$b) as $i (1; . * $in);
|
||||
26
Task/Jacobsthal-numbers/Jq/jacobsthal-numbers-2.jq
Normal file
26
Task/Jacobsthal-numbers/Jq/jacobsthal-numbers-2.jq
Normal file
|
|
@ -0,0 +1,26 @@
|
|||
def jacobsthal:
|
||||
. as $n
|
||||
| ( (2|power($n)) - (if ($n%2 == 0) then 1 else -1 end)) | divmod(3)[0];
|
||||
|
||||
def jacobsthalLucas:
|
||||
. as $n
|
||||
| (2|power($n)) + (if ($n%2 == 0) then 1 else -1 end);
|
||||
|
||||
def tasks:
|
||||
def pp($width): chunks(5) | map(lpad($width)) | join("");
|
||||
|
||||
[range(0;30) | jacobsthal] as $js
|
||||
| "First 30 Jacobsthal numbers:",
|
||||
( $js | pp(12)),
|
||||
|
||||
"\nFirst 30 Jacobsthal-Lucas numbers:",
|
||||
( [range(0;30) | jacobsthalLucas] | pp(12)),
|
||||
|
||||
"\nFirst 20 Jacobsthal oblong numbers:",
|
||||
( [range(0;20) | $js[.] * $js[1+.]] | pp(14)),
|
||||
|
||||
"\nFirst 11 Jacobsthal primes:",
|
||||
limit(11; range(0; infinite) | jacobsthal | select(is_prime))
|
||||
;
|
||||
|
||||
tasks
|
||||
23
Task/Jacobsthal-numbers/Julia/jacobsthal-numbers.julia
Normal file
23
Task/Jacobsthal-numbers/Julia/jacobsthal-numbers.julia
Normal file
|
|
@ -0,0 +1,23 @@
|
|||
using Lazy
|
||||
using Primes
|
||||
|
||||
J(n) = (2^n - (-1)^n) ÷ 3
|
||||
L(n) = 2^n + (-1)^n
|
||||
|
||||
Jacobsthal = @>> Lazy.range(0) map(J)
|
||||
JLucas = @>> Lazy.range(0) map(L)
|
||||
Joblong = @>> Lazy.range(big"0") map(n -> J(n) * J(n + 1))
|
||||
Jprimes = @>> Lazy.range(big"0") map(J) filter(isprime)
|
||||
|
||||
function printrows(title, vec, columnsize = 15, columns = 5, rjust=true)
|
||||
println(title)
|
||||
for (i, n) in enumerate(vec)
|
||||
print((rjust ? lpad : rpad)(n, columnsize), i % columns == 0 ? "\n" : "")
|
||||
end
|
||||
println()
|
||||
end
|
||||
|
||||
printrows("Thirty Jacobsthal numbers:", collect(take(30, Jacobsthal)))
|
||||
printrows("Thirty Jacobsthal-Lucas numbers:", collect(take(30, JLucas)))
|
||||
printrows("Twenty oblong Jacobsthal numbers:", collect(take(20, Joblong)))
|
||||
printrows("Fifteen Jacabsthal prime numbers:", collect(take(15, Jprimes)), 40, 1, false)
|
||||
18
Task/Jacobsthal-numbers/Mathematica/jacobsthal-numbers.math
Normal file
18
Task/Jacobsthal-numbers/Mathematica/jacobsthal-numbers.math
Normal file
|
|
@ -0,0 +1,18 @@
|
|||
ClearAll[Jacobsthal, JacobsthalLucas, JacobsthalOblong]
|
||||
Jacobsthal[n_]:=(2^n-(-1)^n)/3
|
||||
JacobsthalLucas[n_]:=2^n+(-1)^n
|
||||
JacobsthalOblong[n_]:=Jacobsthal[n]Jacobsthal[n+1]
|
||||
Jacobsthal[Range[0, 29]]
|
||||
JacobsthalLucas[Range[0, 29]]
|
||||
JacobsthalOblong[Range[0, 19]]
|
||||
n=0;
|
||||
i=0;
|
||||
Reap[While[n<20,
|
||||
If[
|
||||
PrimeQ[Jacobsthal[i]]
|
||||
,
|
||||
Sow[{i,Jacobsthal[i]}];
|
||||
n++;
|
||||
];
|
||||
i++;
|
||||
]][[2,1]]//Grid
|
||||
73
Task/Jacobsthal-numbers/Nim/jacobsthal-numbers.nim
Normal file
73
Task/Jacobsthal-numbers/Nim/jacobsthal-numbers.nim
Normal file
|
|
@ -0,0 +1,73 @@
|
|||
import std/strutils
|
||||
|
||||
func isPrime(n: Natural): bool =
|
||||
## Return true if "n" is prime.
|
||||
if n < 2: return false
|
||||
if n mod 2 == 0: return n == 2
|
||||
if n mod 3 == 0: return n == 3
|
||||
var step = 2
|
||||
var d = 5
|
||||
while d * d <= n:
|
||||
if n mod d == 0: return false
|
||||
inc d, step
|
||||
step = 6 - step
|
||||
result = true
|
||||
|
||||
iterator jacobsthalSequence(first, second: int): int =
|
||||
## Yield the successive Jacobsthal numbers or
|
||||
## Jacobsthal-Lucas numbers.
|
||||
var prev = first
|
||||
var curr = second
|
||||
yield prev
|
||||
yield curr
|
||||
while true:
|
||||
swap prev, curr
|
||||
curr += curr + prev
|
||||
yield curr
|
||||
|
||||
iterator jacobsthalOblong(): int =
|
||||
## Yield the successive Jacobsthal oblong numbers.
|
||||
var prev = -1
|
||||
for n in jacobsthalSequence(0, 1):
|
||||
if prev >= 0:
|
||||
yield prev * n
|
||||
prev = n
|
||||
|
||||
iterator jacobsthalPrimes(): int =
|
||||
## Yield the successive Jacobsthal prime numbers.
|
||||
for n in jacobsthalSequence(0, 1):
|
||||
if n.isPrime:
|
||||
yield n
|
||||
|
||||
|
||||
echo "First 30 Jacobsthal numbers:"
|
||||
var count = 0
|
||||
for n in jacobsthalSequence(0, 1):
|
||||
inc count
|
||||
stdout.write align($n, 11)
|
||||
if count mod 6 == 0: echo()
|
||||
if count == 30: break
|
||||
|
||||
echo "\nFirst 30 Jacobsthal-Lucas numbers:"
|
||||
count = 0
|
||||
for n in jacobsthalSequence(2, 1):
|
||||
inc count
|
||||
stdout.write align($n, 11)
|
||||
if count mod 6 == 0: echo()
|
||||
if count == 30: break
|
||||
|
||||
echo "\nFirst 20 Jacobsthal oblong numbers:"
|
||||
count = 0
|
||||
for n in jacobsthalOblong():
|
||||
inc count
|
||||
stdout.write align($n, 13)
|
||||
if count mod 5 == 0: echo()
|
||||
if count == 20: break
|
||||
|
||||
echo "\nFirst 10 Jacobsthal prime numbers:"
|
||||
count = 0
|
||||
for n in jacobsthalPrimes():
|
||||
inc count
|
||||
stdout.write align($n, 11)
|
||||
if count mod 5 == 0: echo()
|
||||
if count == 10: break
|
||||
27
Task/Jacobsthal-numbers/OCaml/jacobsthal-numbers.ocaml
Normal file
27
Task/Jacobsthal-numbers/OCaml/jacobsthal-numbers.ocaml
Normal file
|
|
@ -0,0 +1,27 @@
|
|||
let is_prime n =
|
||||
let rec test x =
|
||||
x * x > n || n mod x <> 0 && n mod (x + 2) <> 0 && test (x + 6)
|
||||
in
|
||||
if n < 5
|
||||
then n land 2 <> 0
|
||||
else n land 1 <> 0 && n mod 3 <> 0 && test 5
|
||||
|
||||
let seq_jacobsthal =
|
||||
let rec next b a () = Seq.Cons (a, next (a + a + b) b) in
|
||||
next 1
|
||||
|
||||
let seq_jacobsthal_oblong =
|
||||
let rec next b a () = Seq.Cons (a * b, next (a + a + b) b) in
|
||||
next 1 0
|
||||
|
||||
let () =
|
||||
let show (n, seq, s) =
|
||||
Seq.take n seq
|
||||
|> Seq.fold_left (Printf.sprintf "%s %u") (Printf.sprintf "First %u %s numbers:\n" n s)
|
||||
|> print_endline
|
||||
in
|
||||
List.iter show [
|
||||
30, seq_jacobsthal 0, "Jacobsthal";
|
||||
30, seq_jacobsthal 2, "Jacobsthal-Lucas";
|
||||
20, seq_jacobsthal_oblong, "Jacobsthal oblong";
|
||||
10, Seq.filter is_prime (seq_jacobsthal 0), "Jacobsthal prime"]
|
||||
20
Task/Jacobsthal-numbers/Perl/jacobsthal-numbers.pl
Normal file
20
Task/Jacobsthal-numbers/Perl/jacobsthal-numbers.pl
Normal file
|
|
@ -0,0 +1,20 @@
|
|||
use strict;
|
||||
use warnings;
|
||||
use feature <say state>;
|
||||
use bigint;
|
||||
use List::Util 'max';
|
||||
use ntheory 'is_prime';
|
||||
|
||||
sub table { my $t = 5 * (my $c = 1 + length max @_); ( sprintf( ('%'.$c.'d')x@_, @_) ) =~ s/.{1,$t}\K/\n/gr }
|
||||
|
||||
sub jacobsthal { my($n) = @_; state @J = (0, 1); do { push @J, $J[-1] + 2 * $J[-2]} until @J > $n; $J[$n] }
|
||||
sub jacobsthal_lucas { my($n) = @_; state @JL = (2, 1); do { push @JL, $JL[-1] + 2 * $JL[-2]} until @JL > $n; $JL[$n] }
|
||||
|
||||
my(@j,@jp,$c,$n);
|
||||
push @j, jacobsthal $_ for 0..29;
|
||||
do { is_prime($n = ( 2**++$c - -1**$c ) / 3) and push @jp, $n } until @jp == 20;
|
||||
|
||||
say "First 30 Jacobsthal numbers:\n", table @j;
|
||||
say "First 30 Jacobsthal-Lucas numbers:\n", table map { jacobsthal_lucas $_-1 } 1..30;
|
||||
say "First 20 Jacobsthal oblong numbers:\n", table map { $j[$_-1] * $j[$_] } 1..20;
|
||||
say "First 20 Jacobsthal primes:\n", join "\n", @jp;
|
||||
37
Task/Jacobsthal-numbers/Phix/jacobsthal-numbers.phix
Normal file
37
Task/Jacobsthal-numbers/Phix/jacobsthal-numbers.phix
Normal file
|
|
@ -0,0 +1,37 @@
|
|||
(phixonline)-->
|
||||
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
|
||||
<span style="color: #008080;">function</span> <span style="color: #000000;">jacobsthal</span><span style="color: #0000FF;">(</span><span style="color: #004080;">integer</span> <span style="color: #000000;">n</span><span style="color: #0000FF;">)</span>
|
||||
<span style="color: #008080;">return</span> <span style="color: #7060A8;">floor</span><span style="color: #0000FF;">((</span><span style="color: #7060A8;">power</span><span style="color: #0000FF;">(</span><span style="color: #000000;">2</span><span style="color: #0000FF;">,</span><span style="color: #000000;">n</span><span style="color: #0000FF;">)+</span><span style="color: #7060A8;">odd</span><span style="color: #0000FF;">(</span><span style="color: #000000;">n</span><span style="color: #0000FF;">))/</span><span style="color: #000000;">3</span><span style="color: #0000FF;">)</span>
|
||||
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
|
||||
|
||||
<span style="color: #008080;">function</span> <span style="color: #000000;">jacobsthal_lucas</span><span style="color: #0000FF;">(</span><span style="color: #004080;">integer</span> <span style="color: #000000;">n</span><span style="color: #0000FF;">)</span>
|
||||
<span style="color: #008080;">return</span> <span style="color: #7060A8;">power</span><span style="color: #0000FF;">(</span><span style="color: #000000;">2</span><span style="color: #0000FF;">,</span><span style="color: #000000;">n</span><span style="color: #0000FF;">)+</span><span style="color: #7060A8;">power</span><span style="color: #0000FF;">(-</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #000000;">n</span><span style="color: #0000FF;">)</span>
|
||||
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
|
||||
|
||||
<span style="color: #008080;">function</span> <span style="color: #000000;">jacobsthal_oblong</span><span style="color: #0000FF;">(</span><span style="color: #004080;">integer</span> <span style="color: #000000;">n</span><span style="color: #0000FF;">)</span>
|
||||
<span style="color: #008080;">return</span> <span style="color: #000000;">jacobsthal</span><span style="color: #0000FF;">(</span><span style="color: #000000;">n</span><span style="color: #0000FF;">)*</span><span style="color: #000000;">jacobsthal</span><span style="color: #0000FF;">(</span><span style="color: #000000;">n</span><span style="color: #0000FF;">+</span><span style="color: #000000;">1</span><span style="color: #0000FF;">)</span>
|
||||
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
|
||||
|
||||
<span style="color: #008080;">function</span> <span style="color: #000000;">jba</span><span style="color: #0000FF;">(</span><span style="color: #004080;">string</span> <span style="color: #000000;">fmt</span><span style="color: #0000FF;">,</span> <span style="color: #004080;">sequence</span> <span style="color: #000000;">s</span><span style="color: #0000FF;">,</span> <span style="color: #004080;">integer</span> <span style="color: #000000;">b</span><span style="color: #0000FF;">=</span><span style="color: #000000;">5</span><span style="color: #0000FF;">)</span>
|
||||
<span style="color: #008080;">return</span> <span style="color: #0000FF;">{</span><span style="color: #7060A8;">join_by</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">apply</span><span style="color: #0000FF;">(</span><span style="color: #004600;">true</span><span style="color: #0000FF;">,</span><span style="color: #7060A8;">sprintf</span><span style="color: #0000FF;">,{{</span><span style="color: #000000;">fmt</span><span style="color: #0000FF;">},</span><span style="color: #000000;">s</span><span style="color: #0000FF;">}),</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #000000;">b</span><span style="color: #0000FF;">,</span><span style="color: #008000;">" "</span><span style="color: #0000FF;">)}</span>
|
||||
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
|
||||
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"First 30 Jacobsthal numbers:\n%s\n"</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">jba</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"%9d"</span><span style="color: #0000FF;">,</span><span style="color: #7060A8;">apply</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">tagset</span><span style="color: #0000FF;">(</span><span style="color: #000000;">29</span><span style="color: #0000FF;">,</span><span style="color: #000000;">0</span><span style="color: #0000FF;">),</span><span style="color: #000000;">jacobsthal</span><span style="color: #0000FF;">)))</span>
|
||||
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"First 30 Jacobsthal-Lucas numbers:\n%s\n"</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">jba</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"%9d"</span><span style="color: #0000FF;">,</span><span style="color: #7060A8;">apply</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">tagset</span><span style="color: #0000FF;">(</span><span style="color: #000000;">29</span><span style="color: #0000FF;">,</span><span style="color: #000000;">0</span><span style="color: #0000FF;">),</span><span style="color: #000000;">jacobsthal_lucas</span><span style="color: #0000FF;">)))</span>
|
||||
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"First 20 Jacobsthal oblong numbers:\n%s\n"</span><span style="color: #0000FF;">,</span><span style="color: #000000;">jba</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"%11d"</span><span style="color: #0000FF;">,</span><span style="color: #7060A8;">apply</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">tagset</span><span style="color: #0000FF;">(</span><span style="color: #000000;">19</span><span style="color: #0000FF;">,</span><span style="color: #000000;">0</span><span style="color: #0000FF;">),</span><span style="color: #000000;">jacobsthal_oblong</span><span style="color: #0000FF;">)))</span>
|
||||
<span style="color: #000080;font-style:italic;">--printf(1,"First 10 Jacobsthal primes:\n%s\n", jba("%d",filter(apply(tagset(31,0),jacobsthal),is_prime),1))
|
||||
--hmm(""), fine, but to go further roll out gmp:</span>
|
||||
<span style="color: #008080;">include</span> <span style="color: #004080;">mpfr</span><span style="color: #0000FF;">.</span><span style="color: #000000;">e</span>
|
||||
<span style="color: #004080;">mpz</span> <span style="color: #000000;">z</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">mpz_init</span><span style="color: #0000FF;">()</span>
|
||||
<span style="color: #004080;">integer</span> <span style="color: #000000;">n</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">1</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">found</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">0</span>
|
||||
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"First 20 jacobsthal primes:\n"</span><span style="color: #0000FF;">)</span>
|
||||
<span style="color: #008080;">while</span> <span style="color: #000000;">found</span><span style="color: #0000FF;"><</span><span style="color: #000000;">20</span> <span style="color: #008080;">do</span>
|
||||
<span style="color: #7060A8;">mpz_ui_pow_ui</span><span style="color: #0000FF;">(</span><span style="color: #000000;">z</span><span style="color: #0000FF;">,</span><span style="color: #000000;">2</span><span style="color: #0000FF;">,</span><span style="color: #000000;">n</span><span style="color: #0000FF;">)</span>
|
||||
<span style="color: #7060A8;">mpz_add_ui</span><span style="color: #0000FF;">(</span><span style="color: #000000;">z</span><span style="color: #0000FF;">,</span><span style="color: #000000;">z</span><span style="color: #0000FF;">,</span><span style="color: #7060A8;">odd</span><span style="color: #0000FF;">(</span><span style="color: #000000;">n</span><span style="color: #0000FF;">))</span>
|
||||
<span style="color: #0000FF;">{}</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">mpz_fdiv_q_ui</span><span style="color: #0000FF;">(</span><span style="color: #000000;">z</span><span style="color: #0000FF;">,</span><span style="color: #000000;">z</span><span style="color: #0000FF;">,</span><span style="color: #000000;">3</span><span style="color: #0000FF;">)</span>
|
||||
<span style="color: #008080;">if</span> <span style="color: #7060A8;">mpz_prime</span><span style="color: #0000FF;">(</span><span style="color: #000000;">z</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">then</span>
|
||||
<span style="color: #000000;">found</span> <span style="color: #0000FF;">+=</span> <span style="color: #000000;">1</span>
|
||||
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"%s\n"</span><span style="color: #0000FF;">,{</span><span style="color: #7060A8;">mpz_get_str</span><span style="color: #0000FF;">(</span><span style="color: #000000;">z</span><span style="color: #0000FF;">)})</span>
|
||||
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
|
||||
<span style="color: #000000;">n</span> <span style="color: #0000FF;">+=</span> <span style="color: #000000;">1</span>
|
||||
<span style="color: #008080;">end</span> <span style="color: #008080;">while</span>
|
||||
<!--
|
||||
39
Task/Jacobsthal-numbers/Python/jacobsthal-numbers-1.py
Normal file
39
Task/Jacobsthal-numbers/Python/jacobsthal-numbers-1.py
Normal file
|
|
@ -0,0 +1,39 @@
|
|||
#!/usr/bin/python
|
||||
from math import floor, pow
|
||||
|
||||
def isPrime(n):
|
||||
for i in range(2, int(n**0.5) + 1):
|
||||
if n % i == 0:
|
||||
return False
|
||||
return True
|
||||
|
||||
def odd(n):
|
||||
return n and 1 != 0
|
||||
|
||||
def jacobsthal(n):
|
||||
return floor((pow(2,n)+odd(n))/3)
|
||||
|
||||
def jacobsthal_lucas(n):
|
||||
return int(pow(2,n)+pow(-1,n))
|
||||
|
||||
def jacobsthal_oblong(n):
|
||||
return jacobsthal(n)*jacobsthal(n+1)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
print("First 30 Jacobsthal numbers:")
|
||||
for j in range(0, 30):
|
||||
print(jacobsthal(j), end=" ")
|
||||
|
||||
print("\n\nFirst 30 Jacobsthal-Lucas numbers: ")
|
||||
for j in range(0, 30):
|
||||
print(jacobsthal_lucas(j), end = '\t')
|
||||
|
||||
print("\n\nFirst 20 Jacobsthal oblong numbers: ")
|
||||
for j in range(0, 20):
|
||||
print(jacobsthal_oblong(j), end=" ")
|
||||
|
||||
print("\n\nFirst 10 Jacobsthal primes: ")
|
||||
for j in range(3, 33):
|
||||
if isPrime(jacobsthal(j)):
|
||||
print(jacobsthal(j))
|
||||
169
Task/Jacobsthal-numbers/Python/jacobsthal-numbers-2.py
Normal file
169
Task/Jacobsthal-numbers/Python/jacobsthal-numbers-2.py
Normal file
|
|
@ -0,0 +1,169 @@
|
|||
'''Jacobsthal numbers'''
|
||||
|
||||
from itertools import islice
|
||||
from operator import mul
|
||||
|
||||
|
||||
# jacobsthal :: [Integer]
|
||||
def jacobsthal():
|
||||
'''Infinite sequence of terms of OEIS A001045
|
||||
'''
|
||||
return jacobsthalish(0, 1)
|
||||
|
||||
|
||||
# jacobsthalish :: (Int, Int) -> [Int]
|
||||
def jacobsthalish(*xy):
|
||||
'''Infinite sequence of jacobsthal-type series
|
||||
beginning with a, b
|
||||
'''
|
||||
def go(ab):
|
||||
a, b = ab
|
||||
return a, (b, 2 * a + b)
|
||||
|
||||
return unfoldr(go)(xy)
|
||||
|
||||
|
||||
# ------------------------- TEST -------------------------
|
||||
# main :: IO ()
|
||||
def main():
|
||||
'''First 15 terms each n-step Fibonacci(n) series
|
||||
where n is drawn from [2..8]
|
||||
'''
|
||||
print('\n\n'.join([
|
||||
fShow(*x) for x in [
|
||||
(
|
||||
'terms of the Jacobsthal sequence',
|
||||
30, jacobsthal()),
|
||||
(
|
||||
'Jacobsthal-Lucas numbers',
|
||||
30, jacobsthalish(2, 1)
|
||||
),
|
||||
(
|
||||
'Jacobsthal oblong numbers',
|
||||
20, map(
|
||||
mul, jacobsthal(),
|
||||
drop(1)(jacobsthal())
|
||||
)
|
||||
),
|
||||
(
|
||||
'primes in the Jacobsthal sequence',
|
||||
10, filter(isPrime, jacobsthal())
|
||||
)
|
||||
]
|
||||
]))
|
||||
|
||||
|
||||
# fShow :: (String, Int, [Integer]) -> String
|
||||
def fShow(k, n, xs):
|
||||
'''N tabulated terms of XS, prefixed by the label K
|
||||
'''
|
||||
return f'{n} {k}:\n' + spacedTable(
|
||||
list(chunksOf(5)(
|
||||
[str(t) for t in take(n)(xs)]
|
||||
))
|
||||
)
|
||||
|
||||
|
||||
# ----------------------- GENERIC ------------------------
|
||||
|
||||
# drop :: Int -> [a] -> [a]
|
||||
# drop :: Int -> String -> String
|
||||
def drop(n):
|
||||
'''The sublist of xs beginning at
|
||||
(zero-based) index n.
|
||||
'''
|
||||
def go(xs):
|
||||
if isinstance(xs, (list, tuple, str)):
|
||||
return xs[n:]
|
||||
else:
|
||||
take(n)(xs)
|
||||
return xs
|
||||
return go
|
||||
|
||||
|
||||
# isPrime :: Int -> Bool
|
||||
def isPrime(n):
|
||||
'''True if n is prime.'''
|
||||
if n in (2, 3):
|
||||
return True
|
||||
if 2 > n or 0 == n % 2:
|
||||
return False
|
||||
if 9 > n:
|
||||
return True
|
||||
if 0 == n % 3:
|
||||
return False
|
||||
|
||||
def p(x):
|
||||
return 0 == n % x or 0 == n % (2 + x)
|
||||
|
||||
return not any(map(p, range(5, 1 + int(n ** 0.5), 6)))
|
||||
|
||||
|
||||
# take :: Int -> [a] -> [a]
|
||||
# take :: Int -> String -> String
|
||||
def take(n):
|
||||
'''The prefix of xs of length n,
|
||||
or xs itself if n > length xs.
|
||||
'''
|
||||
def go(xs):
|
||||
return (
|
||||
xs[0:n]
|
||||
if isinstance(xs, (list, tuple))
|
||||
else list(islice(xs, n))
|
||||
)
|
||||
return go
|
||||
|
||||
|
||||
# unfoldr :: (b -> Maybe (a, b)) -> b -> [a]
|
||||
def unfoldr(f):
|
||||
'''Generic anamorphism.
|
||||
A lazy (generator) list unfolded from a seed value by
|
||||
repeated application of f until no residue remains.
|
||||
Dual to fold/reduce.
|
||||
f returns either None, or just (value, residue).
|
||||
For a strict output value, wrap in list().
|
||||
'''
|
||||
def go(x):
|
||||
valueResidue = f(x)
|
||||
while None is not valueResidue:
|
||||
yield valueResidue[0]
|
||||
valueResidue = f(valueResidue[1])
|
||||
return go
|
||||
|
||||
|
||||
# ---------------------- FORMATTING ----------------------
|
||||
|
||||
# chunksOf :: Int -> [a] -> [[a]]
|
||||
def chunksOf(n):
|
||||
'''A series of lists of length n, subdividing the
|
||||
contents of xs. Where the length of xs is not evenly
|
||||
divisible, the final list will be shorter than n.
|
||||
'''
|
||||
def go(xs):
|
||||
return (
|
||||
xs[i:n + i] for i in range(0, len(xs), n)
|
||||
) if 0 < n else None
|
||||
return go
|
||||
|
||||
|
||||
# spacedTable :: [[String]] -> String
|
||||
def spacedTable(rows):
|
||||
'''Tabulated stringification of rows'''
|
||||
columnWidths = [
|
||||
max([len(x) for x in col])
|
||||
for col in zip(*rows)
|
||||
]
|
||||
return '\n'.join([
|
||||
' '.join(
|
||||
map(
|
||||
lambda x, w: x.rjust(w, ' '),
|
||||
row, columnWidths
|
||||
)
|
||||
)
|
||||
for row in rows
|
||||
])
|
||||
|
||||
|
||||
# MAIN ---
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
28
Task/Jacobsthal-numbers/Quackery/jacobsthal-numbers.quackery
Normal file
28
Task/Jacobsthal-numbers/Quackery/jacobsthal-numbers.quackery
Normal file
|
|
@ -0,0 +1,28 @@
|
|||
[ 2 over ** -1 rot ** - 3 / ] is j ( n --> n )
|
||||
|
||||
[ 2 over ** -1 rot ** + ] is jl ( n --> n )
|
||||
|
||||
[ dup 1+ j swap j * ] is jo ( n --> n )
|
||||
|
||||
say "First 30 Jacobsthal numbers:"
|
||||
cr
|
||||
30 times [ i^ j echo sp ]
|
||||
cr cr
|
||||
say "First 30 Jacobsthal-Lucas numbers:"
|
||||
cr
|
||||
30 times [ i^ jl echo sp ]
|
||||
cr cr
|
||||
say "First 20 Jacobsthal oblong numbers:"
|
||||
cr
|
||||
20 times [ i^ jo echo sp ]
|
||||
cr cr
|
||||
say "First 10 Jacobsthal primes:"
|
||||
cr
|
||||
[] 0
|
||||
[ dup j dup isprime iff
|
||||
[ swap dip join ]
|
||||
else drop
|
||||
1+
|
||||
over size 10 = until ]
|
||||
drop
|
||||
witheach [ echo sp ]
|
||||
14
Task/Jacobsthal-numbers/Raku/jacobsthal-numbers.raku
Normal file
14
Task/Jacobsthal-numbers/Raku/jacobsthal-numbers.raku
Normal file
|
|
@ -0,0 +1,14 @@
|
|||
my $jacobsthal = cache lazy 0, 1, * × 2 + * … *;
|
||||
my $jacobsthal-lucas = lazy 2, 1, * × 2 + * … *;
|
||||
|
||||
say "First 30 Jacobsthal numbers:";
|
||||
say $jacobsthal[^30].batch(5)».fmt("%9d").join: "\n";
|
||||
|
||||
say "\nFirst 30 Jacobsthal-Lucas numbers:";
|
||||
say $jacobsthal-lucas[^30].batch(5)».fmt("%9d").join: "\n";
|
||||
|
||||
say "\nFirst 20 Jacobsthal oblong numbers:";
|
||||
say (^∞).map( { $jacobsthal[$_] × $jacobsthal[$_+1] } )[^20].batch(5)».fmt("%11d").join: "\n";
|
||||
|
||||
say "\nFirst 20 Jacobsthal primes:";
|
||||
say $jacobsthal.grep( &is-prime )[^20].join: "\n";
|
||||
52
Task/Jacobsthal-numbers/Red/jacobsthal-numbers.red
Normal file
52
Task/Jacobsthal-numbers/Red/jacobsthal-numbers.red
Normal file
|
|
@ -0,0 +1,52 @@
|
|||
Red ["Jacobsthal numbers"]
|
||||
|
||||
jacobsthal: function [n] [to-integer (2 ** n - (-1 ** n) / 3)]
|
||||
|
||||
lucas: function [n] [2 ** n + (-1 ** n)]
|
||||
|
||||
oblong: function [n] [
|
||||
first split mold multiply to-float jacobsthal n to-float jacobsthal n + 1 #"." ; work around integer overflow
|
||||
]
|
||||
|
||||
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 [1 = n even? n] [return false]
|
||||
limit: sqrt n
|
||||
candidate: 3
|
||||
while [candidate < limit][
|
||||
if n % candidate = 0 [return false]
|
||||
candidate: candidate + 2
|
||||
]
|
||||
true
|
||||
]
|
||||
|
||||
show: function [n fn][
|
||||
cols: length? mold fn n
|
||||
repeat i n [
|
||||
prin [pad 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? jacobsthal n [
|
||||
print jacobsthal n
|
||||
primes: primes + 1
|
||||
]
|
||||
n: n + 1
|
||||
]
|
||||
21
Task/Jacobsthal-numbers/Ruby/jacobsthal-numbers.rb
Normal file
21
Task/Jacobsthal-numbers/Ruby/jacobsthal-numbers.rb
Normal file
|
|
@ -0,0 +1,21 @@
|
|||
require 'prime'
|
||||
|
||||
def jacobsthal(n) = (2**n + n[0])/3
|
||||
def jacobsthal_lucas(n) = 2**n + (-1)**n
|
||||
def jacobsthal_oblong(n) = jacobsthal(n) * jacobsthal(n+1)
|
||||
|
||||
puts "First 30 Jacobsthal numbers:"
|
||||
puts (0..29).map{|n| jacobsthal(n) }.join(" ")
|
||||
|
||||
puts "\nFirst 30 Jacobsthal-Lucas numbers: "
|
||||
puts (0..29).map{|n| jacobsthal_lucas(n) }.join(" ")
|
||||
|
||||
puts "\nFirst 20 Jacobsthal-Oblong numbers: "
|
||||
puts (0..19).map{|n| jacobsthal_oblong(n) }.join(" ")
|
||||
|
||||
puts "\nFirst 10 prime Jacobsthal numbers: "
|
||||
res = (0..).lazy.filter_map do |i|
|
||||
j = jacobsthal(i)
|
||||
j if j.prime?
|
||||
end
|
||||
puts res.take(10).force.join(" ")
|
||||
47
Task/Jacobsthal-numbers/Rust/jacobsthal-numbers.rust
Normal file
47
Task/Jacobsthal-numbers/Rust/jacobsthal-numbers.rust
Normal file
|
|
@ -0,0 +1,47 @@
|
|||
// [dependencies]
|
||||
// rug = "0.3"
|
||||
|
||||
use rug::integer::IsPrime;
|
||||
use rug::Integer;
|
||||
|
||||
fn jacobsthal_numbers() -> impl std::iter::Iterator<Item = Integer> {
|
||||
(0..).map(|x| ((Integer::from(1) << x) - if x % 2 == 0 { 1 } else { -1 }) / 3)
|
||||
}
|
||||
|
||||
fn jacobsthal_lucas_numbers() -> impl std::iter::Iterator<Item = Integer> {
|
||||
(0..).map(|x| (Integer::from(1) << x) + if x % 2 == 0 { 1 } else { -1 })
|
||||
}
|
||||
|
||||
fn jacobsthal_oblong_numbers() -> impl std::iter::Iterator<Item = Integer> {
|
||||
let mut jn = jacobsthal_numbers();
|
||||
let mut n0 = jn.next().unwrap();
|
||||
std::iter::from_fn(move || {
|
||||
let n1 = jn.next().unwrap();
|
||||
let result = Integer::from(&n0 * &n1);
|
||||
n0 = n1;
|
||||
Some(result)
|
||||
})
|
||||
}
|
||||
|
||||
fn jacobsthal_primes() -> impl std::iter::Iterator<Item = Integer> {
|
||||
jacobsthal_numbers().filter(|x| x.is_probably_prime(30) != IsPrime::No)
|
||||
}
|
||||
|
||||
fn main() {
|
||||
println!("First 30 Jacobsthal Numbers:");
|
||||
for (i, n) in jacobsthal_numbers().take(30).enumerate() {
|
||||
print!("{:9}{}", n, if (i + 1) % 5 == 0 { "\n" } else { " " });
|
||||
}
|
||||
println!("\nFirst 30 Jacobsthal-Lucas Numbers:");
|
||||
for (i, n) in jacobsthal_lucas_numbers().take(30).enumerate() {
|
||||
print!("{:9}{}", n, if (i + 1) % 5 == 0 { "\n" } else { " " });
|
||||
}
|
||||
println!("\nFirst 20 Jacobsthal oblong Numbers:");
|
||||
for (i, n) in jacobsthal_oblong_numbers().take(20).enumerate() {
|
||||
print!("{:11}{}", n, if (i + 1) % 5 == 0 { "\n" } else { " " });
|
||||
}
|
||||
println!("\nFirst 20 Jacobsthal primes:");
|
||||
for n in jacobsthal_primes().take(20) {
|
||||
println!("{}", n);
|
||||
}
|
||||
}
|
||||
19
Task/Jacobsthal-numbers/Sidef/jacobsthal-numbers.sidef
Normal file
19
Task/Jacobsthal-numbers/Sidef/jacobsthal-numbers.sidef
Normal file
|
|
@ -0,0 +1,19 @@
|
|||
func jacobsthal(n) {
|
||||
lucasU(1, -2, n)
|
||||
}
|
||||
|
||||
func lucas_jacobsthal(n) {
|
||||
lucasV(1, -2, n)
|
||||
}
|
||||
|
||||
say "First 30 Jacobsthal numbers:"
|
||||
say 30.of(jacobsthal)
|
||||
|
||||
say "\nFirst 30 Jacobsthal-Lucas numbers:"
|
||||
say 30.of(lucas_jacobsthal)
|
||||
|
||||
say "\nFirst 20 Jacobsthal oblong numbers:"
|
||||
say 21.of(jacobsthal).cons(2, {|a,b| a * b })
|
||||
|
||||
say "\nFirst 20 Jacobsthal primes:";
|
||||
say (1..Inf -> lazy.map(jacobsthal).grep{.is_prime}.first(20))
|
||||
59
Task/Jacobsthal-numbers/V-(Vlang)/jacobsthal-numbers.v
Normal file
59
Task/Jacobsthal-numbers/V-(Vlang)/jacobsthal-numbers.v
Normal file
|
|
@ -0,0 +1,59 @@
|
|||
import math.big
|
||||
|
||||
fn jacobsthal(n u32) big.Integer {
|
||||
mut t := big.one_int
|
||||
t=t.lshift(n)
|
||||
mut s := big.one_int
|
||||
if n%2 != 0 {
|
||||
s=s.neg()
|
||||
}
|
||||
t -= s
|
||||
return t/big.integer_from_int(3)
|
||||
}
|
||||
|
||||
fn jacobsthal_lucas(n u32) big.Integer {
|
||||
mut t := big.one_int
|
||||
t=t.lshift(n)
|
||||
mut a := big.one_int
|
||||
if n%2 != 0 {
|
||||
a=a.neg()
|
||||
}
|
||||
return t+a
|
||||
}
|
||||
|
||||
fn main() {
|
||||
mut jac := []big.Integer{len: 30}
|
||||
println("First 30 Jacobsthal numbers:")
|
||||
for i := u32(0); i < 30; i++ {
|
||||
jac[i] = jacobsthal(i)
|
||||
print("${jac[i]:9} ")
|
||||
if (i+1)%5 == 0 {
|
||||
println('')
|
||||
}
|
||||
}
|
||||
|
||||
println("\nFirst 30 Jacobsthal-Lucas numbers:")
|
||||
for i := u32(0); i < 30; i++ {
|
||||
print("${jacobsthal_lucas(i):9} ")
|
||||
if (i+1)%5 == 0 {
|
||||
println('')
|
||||
}
|
||||
}
|
||||
|
||||
println("\nFirst 20 Jacobsthal oblong numbers:")
|
||||
for i := u32(0); i < 20; i++ {
|
||||
print("${jac[i]*jac[i+1]:11} ")
|
||||
if (i+1)%5 == 0 {
|
||||
println('')
|
||||
}
|
||||
}
|
||||
|
||||
/*println("\nFirst 20 Jacobsthal primes:")
|
||||
for n, count := u32(0), 0; count < 20; n++ {
|
||||
j := jacobsthal(n)
|
||||
if j.probably_prime(10) {
|
||||
println(j)
|
||||
count++
|
||||
}
|
||||
}*/
|
||||
}
|
||||
33
Task/Jacobsthal-numbers/Wren/jacobsthal-numbers.wren
Normal file
33
Task/Jacobsthal-numbers/Wren/jacobsthal-numbers.wren
Normal file
|
|
@ -0,0 +1,33 @@
|
|||
import "./big" for BigInt
|
||||
import "./seq" for Lst
|
||||
import "./fmt" for Fmt
|
||||
|
||||
var jacobsthal = Fn.new { |n| ((BigInt.one << n) - ((n%2 == 0) ? 1 : -1)) / 3 }
|
||||
|
||||
var jacobsthalLucas = Fn.new { |n| (BigInt.one << n) + ((n%2 == 0) ? 1 : -1) }
|
||||
|
||||
System.print("First 30 Jacobsthal numbers:")
|
||||
var js = (0..29).map { |i| jacobsthal.call(i) }.toList
|
||||
for (chunk in Lst.chunks(js, 5)) Fmt.print("$,12i", chunk)
|
||||
|
||||
System.print("\nFirst 30 Jacobsthal-Lucas numbers:")
|
||||
var jsl = (0..29).map { |i| jacobsthalLucas.call(i) }.toList
|
||||
for (chunk in Lst.chunks(jsl, 5)) Fmt.print("$,12i", chunk)
|
||||
|
||||
System.print("\nFirst 20 Jacobsthal oblong numbers:")
|
||||
var oblongs = (0..19).map { |i| js[i] * js[i+1] }.toList
|
||||
for (chunk in Lst.chunks(oblongs, 5)) Fmt.print("$,14i", chunk)
|
||||
|
||||
var primes = js.where { |j| j.isProbablePrime(10) }.toList
|
||||
var count = primes.count
|
||||
var i = 31
|
||||
while (count < 20) {
|
||||
var j = jacobsthal.call(i)
|
||||
if (j.isProbablePrime(10)) {
|
||||
primes.add(j)
|
||||
count = count + 1
|
||||
}
|
||||
i = i + 1
|
||||
}
|
||||
System.print("\nFirst 20 Jacobsthal primes:")
|
||||
for (i in 0..19) Fmt.print("$i", primes[i])
|
||||
54
Task/Jacobsthal-numbers/XPL0/jacobsthal-numbers.xpl0
Normal file
54
Task/Jacobsthal-numbers/XPL0/jacobsthal-numbers.xpl0
Normal file
|
|
@ -0,0 +1,54 @@
|
|||
func IsPrime(N); \Return 'true' if N is prime
|
||||
int N, I;
|
||||
[if N <= 2 then return N = 2;
|
||||
if (N&1) = 0 then \even >2\ return false;
|
||||
for I:= 3 to sqrt(N) do
|
||||
[if rem(N/I) = 0 then return false;
|
||||
I:= I+1;
|
||||
];
|
||||
return true;
|
||||
];
|
||||
|
||||
proc Jaco(J2); \Display 30 Jacobsthal (or -Lucas) numbers
|
||||
real J2, J1, J;
|
||||
int N;
|
||||
[RlOut(0, J2);
|
||||
J1:= 1.0;
|
||||
RlOut(0, J1);
|
||||
for N:= 2 to 30-1 do
|
||||
[J:= J1 + 2.0*J2;
|
||||
RlOut(0, J);
|
||||
if rem((N+1)/5) = 0 then CrLf(0);
|
||||
J2:= J1; J1:= J;
|
||||
];
|
||||
CrLf(0);
|
||||
];
|
||||
|
||||
real J, J1, J2, JO;
|
||||
int N;
|
||||
[Format(14, 0);
|
||||
Jaco(0.0);
|
||||
Jaco(2.0);
|
||||
J2:= 1.0;
|
||||
RlOut(0, 0.0);
|
||||
J1:= 1.0;
|
||||
RlOut(0, J1);
|
||||
for N:= 2 to 20-1 do
|
||||
[J:= (J1 + 2.0*J2);
|
||||
JO:= J*J1;
|
||||
RlOut(0, JO);
|
||||
if rem((N+1)/5) = 0 then CrLf(0);
|
||||
J2:= J1; J1:= J;
|
||||
];
|
||||
CrLf(0);
|
||||
J2:= 0.0; J1:= 1.0; N:= 0;
|
||||
loop [J:= J1 + 2.0*J2;
|
||||
if IsPrime(fix(J)) then
|
||||
[RlOut(0, J);
|
||||
N:= N+1;
|
||||
if rem(N/5) = 0 then CrLf(0);
|
||||
if N >= 10 then quit;
|
||||
];
|
||||
J2:= J1; J1:= J;
|
||||
];
|
||||
]
|
||||
Loading…
Add table
Add a link
Reference in a new issue