Stern-Brocot sequence: Difference between revisions

m
(Add BASIC)
m (→‎{{header|Wren}}: Minor tidy)
 
(47 intermediate revisions by 23 users not shown)
Line 11:
#*     1, 1, 2, 1
# Consider the next member of the series, (the third member i.e. 2)
# GOTO 3
#*
#*
#*         ─── Expanding another loop we get: ───
#*
Line 25:
* Create a function/method/subroutine/procedure/... to generate the Stern-Brocot sequence of integers using the method outlined above.
* Show the first fifteen members of the sequence. (This should be: 1, 1, 2, 1, 3, 2, 3, 1, 4, 3, 5, 2, 5, 3, 4)
* Show the (1-based) index of where the numbers 1-to-10 first appearsappear in the sequence.
* Show the (1-based) index of where the number 100 first appears in the sequence.
* Check that the greatest common divisor of all the two consecutive members of the series up to the 1000<sup>th</sup> member, is always one.
Line 39:
;Ref:
* [https://www.youtube.com/watch?v=DpwUVExX27E Infinite Fractions - Numberphile] (Video).
* [http://www.ams.org/samplings/feature-column/fcarc-stern-brocot Trees, Teeth, and Time: The mathematics of clock making].
* [https://oeis.org/A002487 A002487] The On-Line Encyclopedia of Integer Sequences.
<br><br>
 
=={{header|11l}}==
{{trans|Python}}
 
<syntaxhighlight lang="11l">F stern_brocot(predicate = series -> series.len < 20)
V sb = [1, 1]
V i = 0
L predicate(sb)
sb [+]= [sum(sb[i .< i + 2]), sb[i + 1]]
i++
R sb
 
V n_first = 15
print(("The first #. values:\n ".format(n_first))‘ ’stern_brocot(series -> series.len < :n_first)[0 .< n_first])
print()
 
V n_max = 10
L(n_occur) Array(1 .. n_max) [+] [100]
print((‘1-based index of the first occurrence of #3 in the series:’.format(n_occur))‘ ’(stern_brocot(series -> @n_occur !C series).index(n_occur) + 1))
print()
 
V n_gcd = 1000
V s = stern_brocot(series -> series.len < :n_gcd)[0 .< n_gcd]
assert(all(zip(s, s[1..]).map((prev, this) -> gcd(prev, this) == 1)), ‘A fraction from adjacent terms is reducible’)</syntaxhighlight>
 
{{out}}
<pre>
The first 15 values:
[1, 1, 2, 1, 3, 2, 3, 1, 4, 3, 5, 2, 5, 3, 4]
 
1-based index of the first occurrence of 1 in the series: 1
1-based index of the first occurrence of 2 in the series: 3
1-based index of the first occurrence of 3 in the series: 5
1-based index of the first occurrence of 4 in the series: 9
1-based index of the first occurrence of 5 in the series: 11
1-based index of the first occurrence of 6 in the series: 33
1-based index of the first occurrence of 7 in the series: 19
1-based index of the first occurrence of 8 in the series: 21
1-based index of the first occurrence of 9 in the series: 35
1-based index of the first occurrence of 10 in the series: 39
1-based index of the first occurrence of 100 in the series: 1179
</pre>
 
=={{header|360 Assembly}}==
{{trans|Fortran}}
<langsyntaxhighlight lang="360asm">* Stern-Brocot sequence - 12/03/2019
STERNBR CSECT
USING STERNBR,R13 base register
Line 116 ⟶ 158:
SB DC (NN)H'1' sb(nn)
REGEQU
END STERNBR</langsyntaxhighlight>
{{out}}
<pre>
Line 134 ⟶ 176:
</pre>
The nice part is the coding of the sequense:
<langsyntaxhighlight lang="c"> k=2; i=1; j=2;
while(k<nn);
k++; sb[k]=sb[k-i]+sb[k-j];
k++; sb[k]=sb[k-j];
i++; j++;
} </langsyntaxhighlight>
Only five registers are used. No Horner's rule to access sequence items.
<langsyntaxhighlight lang="360asm"> LA R4,SB+2 k=2; @sb(k)
LA R2,SB+2 i=1; @sb(k-i)
LA R3,SB+0 j=2; @sb(k-j)
Line 154 ⟶ 196:
STH R0,0(R4) sb(k)=sb(k-j)
LA R2,2(R2) @sb(k-i)++
BCT R1,LOOP k--; if k>0 then goto loop </langsyntaxhighlight>
 
=={{header|8080 Assembly}}==
<syntaxhighlight lang="8080asm">puts: equ 9 ; CP/M syscall to print a string
 
<lang 8080asm>puts: equ 9 ; CP/M syscall to print a string
org 100h
;;; Generate the first 1200 elements of the Stern-Brocot sequence
Line 293 ⟶ 334:
gcdn: db 'GCD not 1 at: $'
gcdy: db 'GCD of all pairs of consecutive members is 1.$'
seq: db 1,1 ; Sequence stored here</langsyntaxhighlight>
 
{{out}}
Line 303 ⟶ 344:
 
=={{header|8086 Assembly}}==
<syntaxhighlight lang="asm">puts: equ 9
 
<lang asm>puts: equ 9
cpu 8086
bits 16
Line 404 ⟶ 444:
numbuf: db ' $'
nl: db 13,10,'$'
seq: db 1,1</langsyntaxhighlight>
 
{{out}}
Line 413 ⟶ 453:
GCD of all pairs of consecutive members is 1.</pre>
 
=={{header|Action!}}==
<syntaxhighlight lang="action!">PROC Generate(BYTE ARRAY seq INT POINTER count INT minCount,maxVal)
INT i
 
seq(0)=1 seq(1)=1 count^=2 i=1
WHILE count^<minCount OR seq(count^-1)#maxVal AND seq(count^-2)#maxVal
DO
seq(count^)=seq(i-1)+seq(i)
seq(count^+1)=seq(i)
count^==+2 i==+1
OD
RETURN
 
PROC PrintSeq(BYTE ARRAY seq INT count)
=={{header|Ada}}==
INT i
 
PrintF("First %I items:%E",count)
<lang Ada>with Ada.Text_IO, Ada.Containers.Vectors;
FOR i=0 TO count-1
DO
PrintB(seq(i)) Put(32)
OD
PutE() PutE()
RETURN
 
PROC PrintLoc(BYTE ARRAY seq INT seqCount
BYTE ARRAY loc INT locCount)
INT i,j
BYTE value
 
FOR i=0 TO locCount-1
DO
j=0 value=loc(i)
WHILE seq(j)#value
DO
j==+1
OD
PrintF("%B appears at position %I%E",value,j+1)
OD
PutE()
RETURN
 
BYTE FUNC Gcd(BYTE a,b)
BYTE tmp
 
IF a<b THEN
tmp=a a=b b=tmp
FI
 
WHILE b#0
DO
tmp=a MOD b
a=b b=tmp
OD
RETURN (a)
 
PROC PrintGcd(BYTE ARRAY seq INT count)
INT i
 
FOR i=0 TO count-2
DO
IF Gcd(seq(i),seq(i+1))>1 THEN
PrintF("GCD between %I and %I item is greater than 1",i+1,i+2)
RETURN
FI
OD
Print("GCD between all two consecutive items of the sequence is equal 1")
RETURN
 
PROC Main()
BYTE ARRAY seq(2000),loc=[1 2 3 4 5 6 7 8 9 10 100]
INT count
 
Generate(seq,@count,1000,100)
PrintSeq(seq,15)
PrintLoc(seq,count,loc,11)
PrintGcd(seq,1000)
RETURN</syntaxhighlight>
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Stern-Brocot_sequence.png Screenshot from Atari 8-bit computer]
<pre>
First 15 items:
1 1 2 1 3 2 3 1 4 3 5 2 5 3 4
 
1 appears at position 1
2 appears at position 3
3 appears at position 5
4 appears at position 9
5 appears at position 11
6 appears at position 33
7 appears at position 19
8 appears at position 21
9 appears at position 35
10 appears at position 39
100 appears at position 1179
 
GCD between all two consecutive items of the sequence is equal 1
</pre>
 
=={{header|Ada}}==
<syntaxhighlight lang="ada">with Ada.Text_IO, Ada.Containers.Vectors;
 
procedure Sequence is
Line 510 ⟶ 645:
when Constraint_Error => Put_Line("Some GCD > 1; this is wrong!!!") ;
end;
end Sequence;</langsyntaxhighlight>
 
{{out}}
Line 519 ⟶ 654:
First 9 at 35; First 10 at 39; First 100 at 1179.
Correct: The first 999 consecutive pairs are relative prime!</pre>
 
=={{header|ALGOL 68}}==
<syntaxhighlight lang="algol68">BEGIN # find members of the Stern-Brocot sequence: starting from 1, 1 the #
# subsequent members are the previous two members summed followed by #
# the previous #
# iterative Greatest Common Divisor routine, returns the gcd of m and n #
PROC gcd = ( INT m, n )INT:
BEGIN
INT a := ABS m, b := ABS n;
WHILE b /= 0 DO
INT new a = b;
b := a MOD b;
a := new a
OD;
a
END # gcd # ;
# returns an array of the Stern-Brocot sequence up to n #
OP STERNBROCOT = ( INT n )[]INT:
BEGIN
[ 1 : IF ODD n THEN n + 1 ELSE n FI ]INT result;
IF n > 0 THEN
result[ 1 ] := result[ 2 ] := 1;
INT next pos := 2;
FOR i FROM 3 WHILE next pos < n DO
INT p1 = result[ i - 1 ];
result[ next pos +:= 1 ] := p1 + result[ i - 2 ];
result[ next pos +:= 1 ] := p1
OD
FI;
result[ 1 : n ]
END # STERNPROCOT # ;
FLEX[ 1 : 0 ]INT sb := STERNBROCOT 1000; # start with 1000 elements #
# if that isn't enough, more will be added later #
# show the first 15 elements of the sequence #
print( ( "The first 15 elements of the Stern-Brocot sequence are:", newline ) );
FOR i TO 15 DO
print( ( whole( sb[ i ], -3 ) ) )
OD;
print( ( newline, newline ) );
# find where the numbers 1-10 first appear #
INT found 10 := 0;
[ 10 ]INT pos 10; FOR i TO UPB pos 10 DO pos 10[ i ] := 0 OD;
FOR i TO UPB sb WHILE found 10 < 10 DO
INT sb i = sb[ i ];
IF sb i <= UPB pos 10 THEN
IF pos 10[ sb i ] = 0 THEN
# first occurance of this number #
pos 10[ sb i ] := i;
found 10 +:= 1
FI
FI
OD;
print( ( "The first positions of 1..", whole( UPB pos 10, 0 ), " in the sequence are:", newline ) );
FOR i TO UPB pos 10 DO
print( ( whole( i, -2 ), ":", whole( pos 10[ i ], 0 ), " " ) )
OD;
print( ( newline, newline ) );
# find where the number 100 first appears #
BOOL found 100 := FALSE;
FOR i WHILE NOT found 100 DO
IF i > UPB sb THEN
# need more elements #
sb := STERNBROCOT ( UPB sb * 2 )
FI;
IF sb[ i ] = 100 THEN
print( ( "100 first appears at position ", whole( i, 0 ), newline, newline ) );
found 100 := TRUE
FI
OD;
# check that the pairs of elements up to 1000 are coprime #
BOOL all coprime := TRUE;
FOR i FROM 2 TO 1000 WHILE all coprime DO
all coprime := gcd( sb[ i ], sb[ i - 1 ] ) = 1
OD;
print( ( "Element pairs up to 1000 are ", IF all coprime THEN "" ELSE "NOT " FI, "coprime", newline ) )
END</syntaxhighlight>
{{out}}
<pre>
The first 15 elements of the Stern-Brocot sequence are:
1 1 2 1 3 2 3 1 4 3 5 2 5 3 4
 
The first positions of 1..10 in the sequence are:
1:1 2:3 3:5 4:9 5:11 6:33 7:19 8:21 9:35 10:39
 
100 first appears at position 1179
 
Element pairs up to 1000 are coprime</pre>
 
=={{header|ALGOL-M}}==
<syntaxhighlight lang="algolm">begin
integer array S[1:1200];
integer i,ok;
 
integer function gcd(a,b);
integer a,b;
gcd :=
if a>b then gcd(a-b,b)
else if a<b then gcd(a,b-a)
else a;
integer function first(n);
integer n;
begin
integer i;
i := 1;
while S[i]<>n do i := i + 1;
first := i;
end;
S[1] := S[2] := 1;
for i := 2 step 1 until 600 do
begin
S[i*2-1] := S[i] + S[i-1];
S[i*2] := S[i];
end;
 
write("First 15 numbers:");
for i := 1 step 1 until 15 do
begin
if i-i/5*5=1 then write(S[i]) else writeon(S[i]);
end;
 
write("");
write("First occurrence:");
for i := 1 step 1 until 10 do write(i, " at", first(i));
write(100, " at", first(100));
 
ok := 1;
for i := 1 step 1 until 999 do
begin
if gcd(S[i], S[i+1]) <> 1 then
begin
write("gcd",S[i],",",S[i+1],"<> 1");
ok := 0;
end;
end;
if ok = 1 then write("The GCD of each pair of consecutive members is 1.");
end</syntaxhighlight>
{{out}}
<pre>First 15 numbers:
1 1 2 1 3
2 3 1 4 3
5 2 5 3 4
 
First occurrence:
1 at 1
2 at 3
3 at 5
4 at 9
5 at 11
6 at 33
7 at 19
8 at 21
9 at 35
10 at 39
100 at 1179
The GCD of each pair of consecutive members is 1.</pre>
 
=={{header|Amazing Hopper}}==
Version: hopper-FLOW!:
<syntaxhighlight lang="amazing hopper">
#include <flow.h>
#include <flow-flow.h>
 
DEF-MAIN(argv,argc)
CLR-SCR
SET( amount, 1200 )
DIM(amount) AS-ONES( Stern )
 
/* Generate Stern-Brocot sequence: */
GOSUB( Generate Sequence )
PRNL( "Find 15 first: ", [1:19] CGET(Stern) )
 
/* show Stern-Brocot sequence: */
SET( i, 1 ), ITERATE( ++i, LE?(i,10), \
PRN( "First ",i," at "), {i} GOSUB( Find First ), PRNL )
PRN( "First 100 at "), {100} GOSUB( Find First ), PRNL
 
/* check GCD: */
ODD-POS, CGET(Stern), EVEN-POS, CGET(Stern), COMP-GCD, GET-SUMMATORY, DIV-INTO( DIV(amount,2) )
 
IF ( IS-EQ?(1), PRNL("The GCD of every pair of adjacent elements is 1"),\
PRNL("Stern-Brocot Sequence is wrong!") )
END
 
RUTINES
 
DEF-FUN(Find First, n )
RET ( SCAN(1, n, Stern) )
DEF-FUN(Generate Sequence)
SET(i,2)
FOR( LE?(i, DIV(amount,2)), ++i )
[i] GET( Stern ), [ MINUS-ONE(i) ] GET( Stern ), ADD-IT
[ SUB(MUL(i,2),1) ] CPUT( Stern )
[i] GET( Stern ), [MUL(i,2)] CPUT( Stern )
NEXT
RET
</syntaxhighlight>
{{out}}
<pre>
Find 15 first: 1,1,2,1,3,2,3,1,4,3,5,2,5,3,4,1,5,4,7
First 1 at 1
First 2 at 3
First 3 at 5
First 4 at 9
First 5 at 11
First 6 at 33
First 7 at 19
First 8 at 21
First 9 at 35
First 10 at 39
First 100 at 1179
The GCD of every pair of adjacent elements is 1
</pre>
 
=={{header|APL}}==
<syntaxhighlight lang="apl">task←{
stern←{⍵{
⍺←0 ⋄ ⍺⍺≤⍴⍵:⍺⍺↑⍵
(⍺+1)∇⍵,(+/,2⊃⊣)2↑⍺↓⍵
}1 1}
seq←stern 1200 ⍝ Cache 1200 elements
⎕←'First 15 elements:',15↑seq
⎕←'Locations of 1..10:',seq⍳⍳10
⎕←'Location of 100:',seq⍳100
⎕←'All GCDs 1:','no' 'yes'[1+1∧.=2∨/1000↑seq]
}</syntaxhighlight>
 
{{out}}
 
<pre>First 15 elements: 1 1 2 1 3 2 3 1 4 3 5 2 5 3 4
Locations of 1..10: 1 3 5 9 11 33 19 21 35 39
Location of 100: 1179
All GCDs 1: yes </pre>
 
=={{header|AppleScript}}==
<langsyntaxhighlight lang="applescript">use AppleScript version "2.4"
use framework "Foundation"
use scripting additions
 
 
------------------ STERN-BROCOT SEQUENCE -----------------
 
-- sternBrocot :: Generator [Int]
Line 538 ⟶ 910:
 
 
-- TEST ----------------------------------------- TEST -------------------------
on run
set sbs to take(1200, sternBrocot())
Line 589 ⟶ 961:
 
 
-- GENERIC ABSTRACTIONS ------------------------------- GENERIC ------------------------
 
 
-- Absolute value.
Line 601 ⟶ 972:
end if
end abs
 
 
-- Applied to a predicate and a list, `all` determines if all elements
Line 614 ⟶ 986:
end tell
end all
 
 
-- comparing :: (a -> b) -> (a -> a -> Ordering)
Line 658 ⟶ 1,031:
end if
end drop
 
 
-- dropWhile :: (a -> Bool) -> [a] -> [a]
Line 671 ⟶ 1,045:
drop(i - 1, xs)
end dropWhile
 
 
-- enumFrom :: a -> [a]
Line 691 ⟶ 1,066:
end script
end enumFrom
 
 
-- filter :: (a -> Bool) -> [a] -> [a]
Line 704 ⟶ 1,080:
end tell
end filter
 
 
-- fmapGen <$> :: (a -> b) -> Gen [a] -> Gen [b]
Line 720 ⟶ 1,097:
end script
end fmapGen
 
 
-- fst :: (a, b) -> a
Line 729 ⟶ 1,107:
end if
end fst
 
 
-- gcd :: Int -> Int -> Int
Line 743 ⟶ 1,122:
return x
end gcd
 
 
-- head :: [a] -> a
Line 752 ⟶ 1,132:
end if
end head
 
 
-- iterate :: (a -> a) -> a -> Gen [a]
Line 802 ⟶ 1,183:
end if
end min
 
 
-- Lift 2nd class handler function into 1st class script wrapper
Line 844 ⟶ 1,226:
go's |λ|(xs)
end nubBy
 
 
-- partition :: predicate -> List -> (Matches, nonMatches)
Line 862 ⟶ 1,245:
Tuple(ys, zs)
end partition
 
 
-- showJSON :: a -> String
Line 890 ⟶ 1,274:
end if
end showJSON
 
 
-- snd :: (a, b) -> b
Line 922 ⟶ 1,307:
end if
end sortBy
 
 
-- tail :: [a] -> [a]
Line 944 ⟶ 1,330:
end if
end tail
 
 
-- take :: Int -> [a] -> [a]
Line 976 ⟶ 1,363:
end if
end take
 
 
-- takeWhile :: (a -> Bool) -> [a] -> [a]
Line 992 ⟶ 1,380:
end if
end takeWhile
 
 
-- takeWhileGen :: (a -> Bool) -> Gen [a] -> [a]
Line 1,005 ⟶ 1,394:
return ys
end takeWhileGen
 
 
-- Tuple (,) :: a -> b -> (a, b)
Line 1,010 ⟶ 1,400:
{type:"Tuple", |1|:a, |2|:b, length:2}
end Tuple
 
 
-- unlines :: [String] -> String
Line 1,019 ⟶ 1,410:
str
end unlines
 
 
-- zip :: [a] -> [b] -> [(a, b)]
Line 1,024 ⟶ 1,416:
zipWith(Tuple, xs, ys)
end zip
 
 
-- zipWith :: (a -> b -> c) -> [a] -> [b] -> [c]
Line 1,038 ⟶ 1,431:
return lst
end tell
end zipWith</langsyntaxhighlight>
{{Out}}
<pre>[1,1,2,1,3,2,3,1,4,3,5,2,5,3,4]
Line 1,044 ⟶ 1,437:
[100,1179]
true</pre>
 
=={{header|Arturo}}==
 
<syntaxhighlight lang="arturo">sternBrocot: function [mx][
seq: [1 1]
result: [[1 1] [2 1]]
idx: 1
while [idx < mx][
'seq ++ seq\[idx] + seq\[idx - 1]
'result ++ @[@[size seq, last seq]]
'seq ++ seq\[idx]
'result ++ @[@[size seq, last seq]]
inc 'idx
]
return result
]
 
sbs: sternBrocot 1000
 
print ["First 15 terms:" join.with:", " first.n:15 map sbs 'sb -> to :string last sb]
 
print ""
indexes: array.of:101 0
toFind: 101
loop sbs 'sb [
[i, n]: sb
if and? -> contains? 1..100 n -> zero? indexes\[n][
indexes\[n]: i
dec 'toFind
if zero? toFind [
break
]
]
]
 
loop (@1..10) ++ 100 'n ->
print ["Index of first occurrence of number" n ":" indexes\[n]]
 
print ""
 
prev: 1
idx: 1
 
loop sbs 'sb [
[i, n]: sb
if not? one? gcd @[prev n] -> break
prev: n
inc 'idx
if idx > 1000 -> break
]
 
print (idx =< 1000)? -> ["Found two successive terms at index:" idx]
-> "All consecutive terms up to the 1000th member have a GCD equal to one."</syntaxhighlight>
 
{{out}}
 
<pre>First 15 terms: 1, 1, 2, 1, 3, 2, 3, 1, 4, 3, 5, 2, 5, 3, 4
 
Index of first occurrence of number 1 : 1
Index of first occurrence of number 2 : 3
Index of first occurrence of number 3 : 5
Index of first occurrence of number 4 : 9
Index of first occurrence of number 5 : 11
Index of first occurrence of number 6 : 33
Index of first occurrence of number 7 : 19
Index of first occurrence of number 8 : 21
Index of first occurrence of number 9 : 35
Index of first occurrence of number 10 : 39
Index of first occurrence of number 100 : 1179
 
All consecutive terms up to the 1000th member have a GCD equal to one.</pre>
 
=={{header|AutoHotkey}}==
<langsyntaxhighlight AutoHotkeylang="autohotkey">Found := FindOneToX(100), FoundList := ""
Loop, 10
FoundList .= "First " A_Index " found at " Found[A_Index] "`n"
Line 1,122 ⟶ 1,586:
b := Mod(a | 0x0, a := b)
return a
}</langsyntaxhighlight>
{{out}}
<pre>First 15: 1, 1, 2, 1, 3, 2, 3, 1, 4, 3, 5, 2, 5, 3, 4
Line 1,139 ⟶ 1,603:
 
=={{header|BASIC}}==
<syntaxhighlight lang="basic">10 DEFINT A,B,I,J,S: DIM S(1200)
 
<lang basic>10 DEFINT A,B,I,J,S: DIM S(1200)
20 S(1)=1: S(2)=1
30 FOR I=2 TO 600
Line 1,161 ⟶ 1,624:
190 NEXT I
200 PRINT "All GCDs are 1."
210 END</langsyntaxhighlight>
 
{{out}}
Line 1,179 ⟶ 1,642:
All GCDs are 1.
</pre>
 
==={{header|BASIC256}}===
{{trans|FreeBASIC}}
<syntaxhighlight lang="basic256">arraybase 1
max = 2000
global stern
dim stern(max+2)
 
subroutine SternBrocot()
stern[1] = 1
stern[2] = 1
 
i = 2 : n = 2 : ub = stern[?]
 
while i < ub
i += 1
stern[i] = stern[n] + stern[n-1]
i += 1
stern[i] = stern[n]
n += 1
end while
end subroutine
 
function gcd(x, y)
while y
t = y
y = x mod y
x = t
end while
gcd = x
end function
 
call SternBrocot()
 
print "The first 15 are: ";
for i = 1 to 15
print stern[i]; " ";
next i
 
print : print
print "Index First nr."
d = 1
for i = 1 to max
if stern[i] = d then
print i; chr(9); stern[i]
d += 1
if d = 11 then d = 100
if d = 101 then exit for
i = 0
end if
next i
 
print : print
d = 0
for i = 1 to 1000
if gcd(stern[i], stern[i+1]) <> 1 then
d = gcd(stern[i], stern[i+1])
exit for
end if
next i
 
if d = 0 then
print "GCD of two consecutive members of the series up to the 1000th member is 1"
else
print "The GCD for index "; i; " and "; i+1; " = "; d
end if</syntaxhighlight>
{{out}}
<pre>Igual que la entrada de FreeBASIC.</pre>
 
==={{header|QBasic}}===
{{trans|FreeBASIC}}
{{works with|QBasic|1.1}}
<syntaxhighlight lang="qbasic">CONST max = 2000
DIM SHARED stern(max + 2)
 
FUNCTION gcd (x, y)
WHILE y
t = y
y = x MOD y
x = t
WEND
gcd = x
END FUNCTION
 
SUB SternBrocot
stern(1) = 1
stern(2) = 1
i = 2: n = 2: ub = UBOUND(stern)
DO WHILE i < ub
i = i + 1
stern(i) = stern(n) + stern(n - 1)
i = i + 1
stern(i) = stern(n)
n = n + 1
LOOP
END SUB
 
SternBrocot
 
PRINT "The first 15 are: ";
FOR i = 1 TO 15
PRINT stern(i); " ";
NEXT i
 
PRINT : PRINT
PRINT " Index First nr."
d = 1
FOR i = 1 TO max
IF stern(i) = d THEN
PRINT USING " ######"; i; stern(i)
d = d + 1
IF d = 11 THEN d = 100
IF d = 101 THEN EXIT FOR
i = 0
END IF
NEXT i
 
PRINT : PRINT
d = 0
FOR i = 1 TO 1000
IF gcd(stern(i), stern(i + 1)) <> 1 THEN
d = gcd(stern(i), stern(i + 1))
EXIT FOR
END IF
NEXT i
 
IF d <> 0 THEN
PRINT "GCD of two consecutive members of the series up to the 1000th member is 1"
ELSE
PRINT "The GCD for index "; i; " and "; i + 1; " = "; d
END IF</syntaxhighlight>
{{out}}
<pre>Igual que la entrada de FreeBASIC.</pre>
 
==={{header|Yabasic}}===
{{trans|FreeBASIC}}
<syntaxhighlight lang="yabasic">limite = 2000
dim stern(limite+2)
 
sub SternBrocot()
stern(1) = 1
stern(2) = 1
i = 2 : n = 2 : ub = arraysize(stern(),1)
while i < ub
i = i + 1
stern(i) = stern(n) + stern(n -1)
i = i + 1
stern(i) = stern(n)
n = n + 1
wend
end sub
 
sub gcd(p, q)
if q = 0 return p
return gcd(q, mod(p, q))
end sub
 
SternBrocot()
 
print "The first 15 are: ";
for i = 1 to 15
print stern(i), " ";
next i
 
print "\n\n Index First nr."
d = 1
for i = 1 to limite
if stern(i) = d then
print i using "######", stern(i) using "######"
d = d + 1
if d = 11 d = 100
if d = 101 break
i = 0
end if
next i
 
print : print
d = 0
for i = 1 to 1000
if gcd(stern(i), stern(i+1)) <> 1 then
d = gcd(stern(i), stern(i+1))
break
end if
next i
 
if d = 0 then
print "GCD of two consecutive members of the series up to the 1000th member is 1"
else
print "The GCD for index ", i, " and ", i+1, " = ", d
end if</syntaxhighlight>
{{out}}
<pre>Igual que la entrada de FreeBASIC.</pre>
 
=={{header|BCPL}}==
<syntaxhighlight lang="bcpl">get "libhdr"
 
manifest $( AMOUNT = 1200 $)
 
let gcd(a,b) =
a>b -> gcd(a-b, b),
a<b -> gcd(a, b-a),
a
 
let mkstern(s, n) be
$( s!1 := 1
s!2 := 1
for i=2 to n/2 do
$( s!(i*2-1) := s!i + s!(i-1)
s!(i*2) := s!i
$)
$)
 
let find(v, n, max) = valof
for i=1 to max
if v!i=n then resultis i
 
let findwrite(v, n, max) be
writef("%I3 at %I4*N", n, find(v, n, max))
 
let start() be
$( let stern = vec AMOUNT
mkstern(stern, AMOUNT)
writes("First 15 numbers: ")
for i=1 to 15 do writef("%N ", stern!i)
writes("*N*NFirst occurrence:*N")
for i=1 to 10 do findwrite(stern, i, AMOUNT)
findwrite(stern, 100, AMOUNT)
if valof
$( for i=2 to AMOUNT
unless gcd(stern!i, stern!(i-1)) = 1
resultis false
resultis true
$) then
writes("*NThe GCD of each pair of consecutive members is 1.*N")
$)</syntaxhighlight>
{{out}}
<pre>First 15 numbers: 1 1 2 1 3 2 3 1 4 3 5 2 5 3 4
 
First occurrence:
1 at 1
2 at 3
3 at 5
4 at 9
5 at 11
6 at 33
7 at 19
8 at 21
9 at 35
10 at 39
100 at 1179
 
The GCD of each pair of consecutive members is 1.</pre>
 
=={{header|C}}==
Recursive function.
<langsyntaxhighlight lang="c">#include <stdio.h>
 
typedef unsigned int uint;
Line 1,219 ⟶ 1,941:
 
return 0;
}</langsyntaxhighlight>
{{out}}
<pre>
Line 1,237 ⟶ 1,959:
</pre>
The above <code>f()</code> can be replaced by the following, which is much faster but probably less obvious as to how it arrives from the recurrence relations.
<langsyntaxhighlight lang="c">uint f(uint n)
{
uint a = 1, b = 0;
Line 1,246 ⟶ 1,968:
}
return b;
}</langsyntaxhighlight>
 
=={{header|C sharp|C#}}==
<langsyntaxhighlight lang="csharp">using System;
using System.Collections.Generic;
using System.Linq;
Line 1,274 ⟶ 1,996:
" series up to the {0}th item is {1}always one.", max, good ? "" : "not ");
}
}</langsyntaxhighlight>
{{out}}
<pre>The first 15 items In the Stern-Brocot sequence: 1, 1, 2, 1, 3, 2, 3, 1, 4, 3, 5, 2, 5, 3, 4
Line 1,295 ⟶ 2,017:
 
=={{header|C++}}==
<langsyntaxhighlight lang="cpp">
#include <iostream>
#include <iomanip>
Line 1,346 ⟶ 2,068:
return 0;
}
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 1,389 ⟶ 2,111:
 
=={{header|Clojure}}==
<langsyntaxhighlight lang="clojure">;; each step adds two items
(defn sb-step [v]
(let [i (quot (count v) 2)]
Line 1,422 ⟶ 2,144:
true)
 
(report-sb)</langsyntaxhighlight>
 
{{Output}}
Line 1,442 ⟶ 2,164:
 
===Clojure: Using Lazy Sequences===
<langsyntaxhighlight lang="clojure">(ns test-p.core)
(defn gcd
"(gcd a b) computes the greatest common divisor of a and b."
Line 1,474 ⟶ 2,196:
(println (every? (fn [[ith ith-plus-1]] (= (gcd ith ith-plus-1) 1))
one-thousand-pairs))
</syntaxhighlight>
</lang>
{{Output}}
 
Line 1,492 ⟶ 2,214:
true
</pre>
 
=={{header|CLU}}==
<syntaxhighlight lang="clu">stern = proc (n: int) returns (array[int])
s: array[int] := array[int]$fill(1, n, 1)
for i: int in int$from_to(2, n/2) do
s[i*2-1] := s[i] + s[i-1]
s[i*2] := s[i]
end
return (s)
end stern
 
gcd = proc (a,b: int) returns (int)
while b ~= 0 do
a, b := b, a//b
end
return (a)
end gcd
 
find = proc [T: type] (a: array[T], val: T) returns (int) signals (not_found)
where T has equal: proctype (T,T) returns (bool)
for i: int in array[T]$indexes(a) do
if a[i] = val then return (i) end
end
signal not_found
end find
 
start_up = proc ()
po: stream := stream$primary_output()
s: array[int] := stern(1200)
stream$puts(po, "First 15 numbers:")
for i: int in int$from_to(1, 15) do
stream$puts(po, " " || int$unparse(s[i]))
end
stream$putl(po, "")
for i: int in int$from_to(1, 10) do
stream$putl(po, "First " || int$unparse(i) || " at " ||
int$unparse(find[int](s, i)))
end
stream$putl(po, "First 100 at " || int$unparse(find[int](s, 100)))
 
begin
for i: int in int$from_to(2, array[int]$high(s)) do
if gcd(s[i-1], s[i]) ~= 1 then
exit gcd_not_one(i)
end
end
stream$putl(po, "The GCD of every pair of adjacent elements is 1.")
end except when gcd_not_one(i: int):
stream$putl(po, "The GCD of the pair at " || int$unparse(i) || " is not 1.")
end
end start_up</syntaxhighlight>
{{out}}
<pre>First 15 numbers: 1 1 2 1 3 2 3 1 4 3 5 2 5 3 4
First 1 at 1
First 2 at 3
First 3 at 5
First 4 at 9
First 5 at 11
First 6 at 33
First 7 at 19
First 8 at 21
First 9 at 35
First 10 at 39
First 100 at 1179
The GCD of every pair of adjacent elements is 1.</pre>
 
=={{header|Common Lisp}}==
<langsyntaxhighlight lang="lisp">(defun stern-brocot (numbers)
(declare ((or null (vector integer)) numbers))
(cond ((null numbers)
Line 1,549 ⟶ 2,338:
(first-1-to-10)
(first-100)
(check-gcd))</langsyntaxhighlight>
{{out}}
<pre>First 15: 1 1 2 1 3 2 3 1 4 3 5 2 5 3 4
Line 1,564 ⟶ 2,353:
First 100 at 1179
Correct. The GCDs of all the two consecutive numbers are 1.</pre>
 
=={{header|Cowgol}}==
<syntaxhighlight lang="cowgol">include "cowgol.coh";
 
# Redefining these is enough to change the type and length everywhere,
# but arrays are 0-based so you need one extra element.
typedef Stern is uint8; # 8-bit math is enough for the numbers we need
var stern: Stern[1201]; # Array containing Stern-Brocot sequence
 
# Fill up the Stern-Brocot array
sub GenStern() is
stern[1] := 1;
stern[2] := 1;
 
var i: @indexof stern := 1;
var last: @indexof stern := @sizeof stern / 2;
while i <= last loop
stern[i*2-1] := stern[i] + stern[i-1];
stern[i*2] := stern[i];
i := i + 1;
end loop;
end sub;
 
# Find the first location of a given number
sub FindFirst(n: Stern): (i: @indexof stern) is
i := 1;
while i < @sizeof stern and stern[i] != n loop
i := i + 1;
end loop;
end sub;
 
GenStern(); # Generate sequence
 
# Print the first 15 numbers
var i: @indexof stern := 1;
while i <= 15 loop
print_i32(stern[i] as uint32);
print_char(' ');
i := i + 1;
end loop;
print_nl();
 
# Print the first occurrence of 1..10
var j: Stern := 1;
while j <= 10 loop
print_i32(FindFirst(j) as uint32);
print_char(' ');
j := j + 1;
end loop;
print_nl();
 
# Print the first occurrence of 100
print_i32(FindFirst(100) as uint32);
print_nl();
 
# Check that all GCDs of consecutive pairs are 1
sub gcd(a: Stern, b: Stern): (r: Stern) is
while a != b loop
if a > b then
a := a - b;
else
b := b - a;
end if;
end loop;
r := a;
end sub;
 
i := 1;
while i < @sizeof stern / 2 loop
if gcd(stern[i], stern[i+1]) != 1 then
print("GCD not 1 at: ");
print_i32(i as uint32);
print_nl();
ExitWithError();
end if;
i := i + 1;
end loop;
 
print("All GCDs are 1.\n");</syntaxhighlight>
 
{{out}}
<pre>1 1 2 1 3 2 3 1 4 3 5 2 5 3 4
1 3 5 9 11 33 19 21 35 39
1179
All GCDs are 1.</pre>
 
=={{header|D}}==
{{trans|Python}}
<langsyntaxhighlight lang="d">import std.stdio, std.numeric, std.range, std.algorithm;
 
/// Generates members of the stern-brocot series, in order,
Line 1,595 ⟶ 2,469:
assert(zip(s, s.dropOne).all!(ss => ss[].gcd == 1),
"A fraction from adjacent terms is reducible.");
}</langsyntaxhighlight>
{{out}}
<pre>The first 15 values:
Line 1,613 ⟶ 2,487:
 
This uses a queue from the Queue/usage Task:
<langsyntaxhighlight lang="d">import std.stdio, std.algorithm, std.range, std.numeric, queue_usage2;
 
struct SternBrocot {
Line 1,630 ⟶ 2,504:
void main() {
SternBrocot().drop(50_000_000).front.writeln;
}</langsyntaxhighlight>
{{out}}
<pre>7004</pre>
Line 1,636 ⟶ 2,510:
<b>Direct Version:</b>
{{trans|C}}
<langsyntaxhighlight lang="d">void main() {
import std.stdio, std.numeric, std.range, std.algorithm, std.bigint, std.conv;
 
Line 1,663 ⟶ 2,537:
 
sternBrocot(10.BigInt ^^ 20_000).text.length.writeln;
}</langsyntaxhighlight>
{{out}}
<pre>The first 15 values:
Line 1,680 ⟶ 2,554:
1-based index of the first occurrence of 100 in the series: 1179
7984</pre>
 
=={{header|EasyLang}}==
{{trans|Lua}}
<syntaxhighlight>
global sb[] .
proc sternbrocot n . .
sb[] = [ 1 1 ]
pos = 2
repeat
c = sb[pos]
sb[] &= c + sb[pos - 1]
sb[] &= c
pos += 1
until len sb[] >= n
.
.
func first v .
for i to len sb[]
if v <> 0
if sb[i] = v
return i
.
else
if sb[i] <> 0
return i
.
.
.
return 0
.
func gcd x y .
if y = 0
return x
.
return gcd y (x mod y)
.
func$ task5 .
for i to 1000
if gcd sb[i] sb[i + 1] <> 1
return "FAIL"
.
.
return "PASS"
.
sternbrocot 10000
write "Task 2: "
for i to 15
write sb[i] & " "
.
print "\n\nTask 3:"
for i to 10
print "\t" & i & " " & first i
.
print "\nTask 4: " & first 100
print "\nTask 5: " & task5
</syntaxhighlight>
 
{{out}}
<pre>
Task 2: 1 1 2 1 3 2 3 1 4 3 5 2 5 3 4
 
Task 3:
1 1
2 3
3 5
4 9
5 11
6 33
7 19
8 21
9 35
10 39
 
Task 4: 1179
 
Task 5: PASS
</pre>
 
 
=={{header|EchoLisp}}==
=== Function ===
<langsyntaxhighlight lang="lisp">
;; stern (2n ) = stern (n)
;; stern(2n+1) = stern(n) + stern(n+1)
Line 1,693 ⟶ 2,645:
(else (let ((m (/ (1- n) 2))) (+ (stern m) (stern (1+ m)))))))
(remember 'stern)
</syntaxhighlight>
</lang>
{{out}}
<langsyntaxhighlight lang="lisp">
; generate the sequence and check GCD
(for ((n 10000))
Line 1,716 ⟶ 2,668:
(stern 900000) → 446
(stern 900001) → 2479
</syntaxhighlight>
</lang>
 
=== Stream ===
From [https://oeis.org/A002487 A002487], if we group the elements by two, we get (uniquely) all the rationals. Another way to generate the rationals, hence the stern sequence, is to iterate the function f(x) = floor(x) + 1 - fract(x).
 
<langsyntaxhighlight lang="lisp">
;; grouping
(for ((i (in-range 2 40 2))) (write (/ (stern i)(stern (1+ i)))))
Line 1,735 ⟶ 2,687:
 
→ 1/2 1/3 2/3 1/4 3/5 2/5 3/4 1/5 4/7 3/8 5/7 2/7 5/8 3/7 4/5 1/6 5/9 4/11 7/10
</syntaxhighlight>
</lang>
 
=={{header|Elixir}}==
<langsyntaxhighlight lang="elixir">defmodule SternBrocot do
def sequence do
Stream.unfold({0,{1,1}}, fn {i,acc} ->
Line 1,765 ⟶ 2,717:
end
 
SternBrocot.task</langsyntaxhighlight>
 
{{out}}
Line 1,787 ⟶ 2,739:
=={{header|F_Sharp|F#}}==
===The function===
<langsyntaxhighlight lang="fsharp">
// Generate Stern-Brocot Sequence. Nigel Galloway: October 11th., 2018
let sb=Seq.unfold(fun (n::g::t)->Some(n,[g]@t@[n+g;g]))[1;1]
</syntaxhighlight>
</lang>
===The Task===
Uses [[Greatest_common_divisor#F.23]]
<langsyntaxhighlight lang="fsharp">
sb |> Seq.take 15 |> Seq.iter(printf "%d ");printfn ""
[1..10] |> List.map(fun n->(n,(sb|>Seq.findIndex(fun g->g=n))+1)) |> List.iter(printf "%A ");printfn ""
printfn "%d" ((sb|>Seq.findIndex(fun g->g=100))+1)
printfn "There are %d consecutive members, of the first thousand members, with GCD <> 1" (sb |> Seq.take 1000 |>Seq.pairwise |> Seq.filter(fun(n,g)->gcd n g <> 1) |> Seq.length)
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 1,809 ⟶ 2,761:
=={{header|Factor}}==
Using the alternative function given in the C example for computing the Stern-Brocot sequence.
<langsyntaxhighlight lang="factor">USING: formatting io kernel lists lists.lazy locals math
math.ranges prettyprint sequences ;
IN: rosetta-code.stern-brocot
Line 1,839 ⟶ 2,791:
: main ( -- ) first15 first-appearances gcd-test ;
 
MAIN: main</langsyntaxhighlight>
{{out}}
<pre>
Line 1,854 ⟶ 2,806:
First 10 at Stern #39.
First 100 at Stern #1179.
All GCDs are 1.
</pre>
 
=={{header|Forth}}==
<syntaxhighlight lang="forth">: stern ( n -- x : return N'th item of Stern-Brocot sequence)
dup 2 >= if
2 /mod swap if
dup 1+ recurse
swap recurse
+
else
recurse
then
then
;
 
: first ( n -- x : return X such that stern X = n )
1 begin over over stern <> while 1+ repeat
swap drop
;
 
: gcd ( a b -- a gcd b )
begin swap over mod dup 0= until drop
;
: task
( Print first 15 numbers )
." First 15: " 1 begin dup stern . 1+ dup 15 > until
drop cr
( Print first occurrence of 1..10 )
1 begin
." First " dup . ." at " dup first .
1+ cr
dup 10 > until
drop
( Print first occurrence of 100 )
." First 100 at " 100 first . cr
( Check that the GCD of each adjacent pair up to 1000 is 1 )
-1 2 begin
dup stern over 1- stern gcd 1 =
rot and swap
1+
dup 1000 > until
swap if
." All GCDs are 1."
drop
else
." GCD <> 1 at: " .
then
cr
;
 
task
bye</syntaxhighlight>
 
{{out}}
 
<pre>First 15: 1 1 2 1 3 2 3 1 4 3 5 2 5 3 4
First 1 at 1
First 2 at 3
First 3 at 5
First 4 at 9
First 5 at 11
First 6 at 33
First 7 at 19
First 8 at 21
First 9 at 35
First 10 at 39
First 100 at 1179
All GCDs are 1.
</pre>
Line 1,860 ⟶ 2,884:
{{trans|VBScript}}
===Fortran IV===
<langsyntaxhighlight lang="fortran">* STERN-BROCOT SEQUENCE - FORTRAN IV
DIMENSION ISB(2400)
NN=2400
Line 1,890 ⟶ 2,914:
103 FORMAT(1X,'FIRST',I4,' AT ',I4)
5 CONTINUE
END </langsyntaxhighlight>
{{out}}
<pre>
Line 1,909 ⟶ 2,933:
</pre>
===Fortran 90===
<langsyntaxhighlight lang="fortran"> ! Stern-Brocot sequence - Fortran 90
parameter (nn=2400)
dimension isb(nn)
Line 1,930 ⟶ 2,954:
write(*,"(1x,'First',i4,' at ',i4)") jj,i
end do
end </langsyntaxhighlight>
{{out}}
<pre>
Line 1,949 ⟶ 2,973:
 
=={{header|FreeBASIC}}==
<langsyntaxhighlight lang="freebasic">' version 02-03-2019
' compile with: fbc -s console
 
Line 2,030 ⟶ 3,054:
Print : Print "hit any key to end program"
Sleep
End</langsyntaxhighlight>
{{out}}
<pre>The first 15 are: 1 1 2 1 3 2 3 1 4 3 5 2 5 3 4
Line 2,050 ⟶ 3,074:
 
=={{header|Go}}==
<langsyntaxhighlight lang="go">package main
 
import (
Line 2,097 ⟶ 3,121:
}
return x
}</langsyntaxhighlight>
<langsyntaxhighlight lang="go">// SB implements the Stern-Brocot sequence.
//
// Generator() satisfies RC Task 1. For remaining tasks, Generator could be
Line 2,171 ⟶ 3,195:
}
}
}</langsyntaxhighlight>
{{out}}
<pre>
Line 2,213 ⟶ 3,237:
 
=={{header|Haskell}}==
<langsyntaxhighlight lang="haskell">import Data.List (elemIndex)
 
sb :: [Int]
sb = 1 : 1 : f (tail sb) sb
where
f (a : aa) (b : bb) = a + b : a : f aa bb
 
main :: IO ()
Line 2,225 ⟶ 3,249:
print
[ (i, 1 + (\(Just i) -> i) (elemIndex i sb))
| i <- [1 .. 10] ++<> [100] ]
]
print $ all (\(a, b) -> 1 == gcd a b) $ take 1000 $ zip sb (tail sb)</lang>
print $
all (\(a, b) -> 1 == gcd a b) $
take 1000 $ zip sb (tail sb)</syntaxhighlight>
{{out}}
<pre>[1,1,2,1,3,2,3,1,4,3,5,2,5,3,4]
Line 2,234 ⟶ 3,261:
Or, expressed in terms of iterate:
 
<syntaxhighlight lang ="haskell">import Data.ListFunction (nubBy, sortByon)
import Data.List (nubBy, sortOn)
import Data.Ord (comparing)
 
import Data.Monoid ((<>))
------------------ STERN-BROCOT SEQUENCE -----------------
import Data.Function (on)
 
sternBrocot :: [Int]
sternBrocot = head <$> iterate go [1, 1]
where
let go (a:b:xs) = (b : xs) <> [a + b, b]
in head go (a : b : xs) = (b : xs) <$> iterate[a go+ [1b, 1b]
 
-- TEST ------------------------------------ TEST -------------------------
main :: IO ()
main = do
Line 2,250 ⟶ 3,278:
print $
take 10 $
nubBy (on (==) fst) $
sortOn fst $
sortBy (comparing fst) $ takeWhile ((110 >=) . fst) $ zip sternBrocot [1 ..]
print $ take 1 $ dropWhile takeWhile ((100110 />=) . fst) $ zip sternBrocot [1 ..]
zip sternBrocot [1 ..]
print $ (all ((1 ==) . uncurry gcd) . (zip <*> tail)) $ take 1000 sternBrocot</lang>
print $
take 1 $
dropWhile ((100 /=) . fst) $
zip sternBrocot [1 ..]
print $
(all ((1 ==) . uncurry gcd) . (zip <*> tail)) $
take 1000 sternBrocot</syntaxhighlight>
{{Out}}
<pre>[1,1,2,1,3,2,3,1,4,3,5,2,5,3,4]
Line 2,261 ⟶ 3,296:
 
=={{header|J}}==
 
We have two different kinds of list specifications here (length of the sequence, and the presence of certain values in the sequence). Also the underlying list generation mechanism is somewhat arbitrary. So let's generate the sequence iteratively and provide a truth valued function of the intermediate sequences to determine when we have generated one which is adequately long:
 
<langsyntaxhighlight Jlang="j">sternbrocot=:1 :0
ind=. 0
seq=. 1 1
Line 2,271 ⟶ 3,305:
seq=. seq, +/\. seq {~ _1 0 +ind
end.
)</langsyntaxhighlight>
 
(Grammatical aside: this is an adverb which generates a noun without taking any x/y arguments. So usage is: <code>u sternbrocot</code>. J does have precedence rules, just not very many of them. Users of other languages can get a rough idea of the grammatical terms like this: adverb is approximately like a macro, verb approximately like a function and noun is approximately like a number. Also x and y are J's names for left and right noun arguments, and u and v are J's names for left and right verb arguments. An adverb has a left verb argument. There are some other important constraints but that's probably more than enough detail for this task.)
Line 2,277 ⟶ 3,311:
First fifteen members of the sequence:
 
<langsyntaxhighlight Jlang="j"> 15{.(15<:#) sternbrocot
1 1 2 1 3 2 3 1 4 3 5 2 5 3 4</langsyntaxhighlight>
 
One based indices of where numbers 1-10 first appear in the sequence:
 
<langsyntaxhighlight Jlang="j"> 1+(10 e. ]) sternbrocot i.1+i.10
1 3 5 9 11 33 19 21 35 39</langsyntaxhighlight>
 
One based index of where the number 100 first appears:
 
<langsyntaxhighlight Jlang="j"> 1+(100 e. ]) sternbrocot i. 100
1179</langsyntaxhighlight>
 
List of distinct greatest common divisors of adjacent number pairs from a sternbrocot sequence which includes the first 1000 elements:
 
<langsyntaxhighlight Jlang="j"> ~.2 +./\ (1000<:#) sternbrocot
1</langsyntaxhighlight>
 
=={{header|Java}}==
{{works with|Java|1.5+}}
This example generates the first 1200 members of the sequence since that is enough to cover all of the tests in the description. It borrows the <code>gcd</code> method from <code>BigInteger</code> rather than using its own.
<langsyntaxhighlight lang="java5">import java.math.BigInteger;
import java.util.LinkedList;
 
Line 2,331 ⟶ 3,365:
System.out.println("All GCDs are" + (failure ? " not" : "") + " 1");
}
}</langsyntaxhighlight>
{{out}}
<pre>The first 15 elements are: [1, 1, 2, 1, 3, 2, 3, 1, 4, 3, 5, 2, 5, 3, 4]
Line 2,349 ⟶ 3,383:
=== Stern-Brocot Tree ===
{{works with|Java|8}}
<langsyntaxhighlight lang="java">import java.awt.*;
import javax.swing.*;
 
Line 2,411 ⟶ 3,445:
});
}
}</langsyntaxhighlight>
[[File:stern_brocot_tree_java.gif]]
 
=={{header|JavaScript}}==
<langsyntaxhighlight JavaScriptlang="javascript">(() => {
'use strict';
 
Line 2,739 ⟶ 3,773:
// MAIN ---
return main();
})();</langsyntaxhighlight>
{{Out}}
<pre>[1,1,2,1,3,2,3,1,4,3,5,2,5,3,4]
Line 2,751 ⟶ 3,785:
 
'''Foundations:'''
<langsyntaxhighlight lang="jq">def until(cond; update):
def _until:
if cond then . else (update | _until) end;
Line 2,762 ⟶ 3,796:
else [.[1], .[0] % .[1]] | rgcd
end;
[a,b] | rgcd ;</langsyntaxhighlight>
'''The A002487 integer sequence:'''
 
Line 2,769 ⟶ 3,803:
The n-th element of the Rosetta Code sequence (counting from 1)
is thus a[n], which accords with the fact that jq arrays have an index origin of 0.
<langsyntaxhighlight lang="jq"># If n is non-negative, then A002487(n)
# generates an array with at least n elements of
# the A002487 sequence;
Line 2,786 ⟶ 3,820:
| if (.[$l-2] == -n) then .
else .[$l + 1] = .[$n] + .[$n+1]
end ) ;</langsyntaxhighlight>
'''The tasks:'''
<langsyntaxhighlight lang="jq"># Generate a stream of n integers beginning with 1,1...
def stern_brocot(n): A002487(n+1) | .[1:n+1][];
 
Line 2,819 ⟶ 3,853:
"",
gcd_task
</syntaxhighlight>
</lang>
{{out}}
<langsyntaxhighlight lang="sh">$ jq -r -n -f stern_brocot.jq
First 15 integers of the Stern-Brocot sequence
as defined in the task description are:
Line 2,853 ⟶ 3,887:
index of 100 is 1179
 
GCDs are all 1</langsyntaxhighlight>
 
=={{header|Julia}}==
{{trans|Python}}
<langsyntaxhighlight lang="julia">using Printf
 
function sternbrocot(f::Function=(x) -> length(x) ≥ 20)::Vector{Int}
rst = Int[1, 1]
i = 32
while !f(rst)
append!(rst, Int[rst[i-1] + rst[i-21], rst[i-2]])
i += 1
end
Line 2,882 ⟶ 3,916:
else
println("Rejected.")
end</langsyntaxhighlight>
 
{{out}}
<pre>
<pre>First 15 elements of Stern-Brocot series:
First 15 elements of Stern-Brocot series:
[1, 1, 2, 1, 3, 1, 3, 2, 4, 1, 4, 3, 4, 1, 5]
[1, 1, 2, 1, 3, 2, 3, 1, 4, 3, 5, 2, 5, 3, 4]
 
Index of first occurrence of 1 in the series: 1
Line 2,892 ⟶ 3,927:
Index of first occurrence of 3 in the series: 5
Index of first occurrence of 4 in the series: 9
Index of first occurrence of 5 in the series: 1511
Index of first occurrence of 6 in the series: 1733
Index of first occurrence of 7 in the series: 2319
Index of first occurrence of 8 in the series: 3121
Index of first occurrence of 9 in the series: 3335
Index of first occurrence of 10 in the series: 5139
Index of first occurrence of 100 in the series: 18551179
 
Assertion: the greatest common divisor of all the two
consecutive members of the series up to the 1000th member, is always one: RejectedConfirmed.</pre>
 
=={{header|Kotlin}}==
<langsyntaxhighlight lang="scala">// version 1.1.0
 
val sbs = mutableListOf(1, 1)
Line 2,967 ⟶ 4,002:
}
println("all one")
}</langsyntaxhighlight>
 
{{out}}
Line 2,992 ⟶ 4,027:
 
=={{header|Lua}}==
<langsyntaxhighlight Lualang="lua">-- Task 1
function sternBrocot (n)
local sbList, pos, c = {1, 1}, 2
Line 3,040 ⟶ 4,075:
for i = 1, 10 do print("\t" .. i, findFirst(sb, i)) end
print("\nTask 4: " .. findFirst(sb, 100))
print("\nTask 5: " .. task5(sb))</langsyntaxhighlight>
{{out}}
<pre>Task 2: 1 1 2 1 3 2 3 1 4 3 5 2 5 3 4
Line 3,060 ⟶ 4,095:
Task 5: PASS</pre>
 
=={{header|OforthMACRO-11}}==
<syntaxhighlight lang="macro11"> .TITLE STNBRC
.MCALL .TTYOUT,.EXIT
AMOUNT = ^D1200
STNBRC::JSR PC,GENSEQ
 
; PRINT FIRST 15
<lang Oforth>: stern(n)
MOV #FST15,R1
JSR PC,PRSTR
MOV #STERN+2,R3
MOV #^D15,R4
1$: MOV (R3)+,R0
JSR PC,PR0
SOB R4,1$
MOV #NEWLINE,R1
JSR PC,PRSTR
 
; PRINT FIRST OCCURRENCE OF 1..10 AND 100
MOV #FSTOCC,R1
JSR PC,PRSTR
MOV #1,R3
2$: JSR PC,PRFST
INC R3
CMP R3,#^D10
BLE 2$
MOV #^D100,R3
JSR PC,PRFST
MOV #NEWLIN,R1
JSR PC,PRSTR
 
; CHECK GCDS OF ADJACENT PAIRS UP TO 1000
MOV #CHKGCD,R1
JSR PC,PRSTR
MOV #STERN+2,R2
MOV #^D999,R5
MOV (R2)+,R3
3$: MOV R3,R4
MOV (R2)+,R3
MOV R3,R0
MOV R4,R1
JSR PC,GCD
DEC R0
BNE 4$
SOB R5,3$
MOV #ALL1,R1
BR 5$
4$: MOV #NOTAL1,R1
5$: JSR PC,PRSTR
.EXIT
 
FST15: .ASCIZ /FIRST 15: /
FSTOCC: .ASCIZ /FIRST OCCURRENCES:/<15><12>
ATWD: .ASCIZ /AT /
CHKGCD: .ASCIZ /CHECKING GCDS OF ADJACENT PAIRS... /
NOTAL1: .ASCII /NOT /
ALL1: .ASCIZ /ALL 1./
NEWLIN: .BYTE 15,12,0
.EVEN
 
; GENERATE STERN-BROCOT SEQUENCE
GENSEQ: MOV #1,R0
MOV R0,STERN+2
MOV R0,STERN+4
MOV #STERN+<2*AMOUNT>,R5
MOV #STERN+2,R0
MOV #STERN+6,R1
MOV (R0)+,R2
1$: MOV R2,R3
MOV (R0)+,R2
MOV R2,R4
ADD R3,R4
MOV R4,(R1)+
MOV R2,(R1)+
CMP R1,R5
BLT 1$
RTS PC
 
; LET R0 = FIRST OCCURRENCE OF R3 IN SEQUENCE
FNDFST: MOV #STERN,R0
1$: CMP (R0)+,R3
BNE 1$
SUB #STERN+2,R0
ASR R0
RTS PC
 
; PRINT FIRST OCC. OF <R3>
PRFST: MOV R3,R0
JSR PC,PR0
MOV #ATWD,R1
JSR PC,PRSTR
JSR PC,FNDFST
JSR PC,PR0
MOV #NEWLIN,R1
JMP PRSTR
 
; LET R0 = GCD(R0,R1)
GCD: CMP R0,R1
BLT 1$
BGT 2$
RTS PC
1$: SUB R0,R1
BR GCD
2$: SUB R1,R0
BR GCD
 
; PRINT NUMBER IN R0 AS DECIMAL
PR0: MOV #4$,R1
1$: MOV #-1,R2
2$: INC R2
SUB #12,R0
BCC 2$
ADD #72,R0
MOVB R0,-(R1)
MOV R2,R0
BNE 1$
3$: MOVB (R1)+,R0
.TTYOUT
BNE 3$
RTS PC
.ASCII /...../
4$: .ASCIZ / /
.EVEN
 
; PRINT STRING IN R1
PRSTR: MOVB (R1)+,R0
.TTYOUT
BNE PRSTR
RTS PC
; STERN-BROCOT BUFFER
STERN: .BLKW AMOUNT+1
.END STNBRC</syntaxhighlight>
{{out}}
<pre>FIRST 15: 1 1 2 1 3 2 3 1 4 3 5 2 5 3 4
FIRST OCCURRENCES:
1 AT 1
2 AT 3
3 AT 5
4 AT 9
5 AT 11
6 AT 33
7 AT 19
8 AT 21
9 AT 35
10 AT 39
100 AT 1179
 
CHECKING GCDS OF ADJACENT PAIRS... ALL 1.</pre>
 
=={{header|MAD}}==
<syntaxhighlight lang="mad"> NORMAL MODE IS INTEGER
VECTOR VALUES FRST15 = $20HFIRST 15 NUMBERS ARE*$
VECTOR VALUES FRSTAT = $6HFIRST ,I3,S1,11HAPPEARS AT ,I4*$
VECTOR VALUES NUMBER = $I4*$
DIMENSION STERN(1200)
STERN(1) = 1
STERN(2) = 1
R GENERATE FIRST 1200 MEMBERS OF THE STERN-BROCOT SEQUENCE
THROUGH GENSEQ, FOR I = 1, 1, I .GE. 600
STERN(I*2-1) = STERN(I) + STERN(I-1)
GENSEQ STERN(I*2) = STERN(I)
 
R PRINT FIRST 15 VALUES OF STERN-BROCOT SEQUENCE
PRINT FORMAT FRST15
THROUGH P15, FOR I = 1, 1, I .G. 15
P15 PRINT ON LINE FORMAT NUMBER, STERN(I)
R PRINT FIRST OCCURRENCE OF 1..10
THROUGH FRST10, FOR I = 1, 1, I .G. 10
FRST10 PRINT FORMAT FRSTAT, I, FIRST.(I)
PRINT FORMAT FRSTAT, 100, FIRST.(100)
R SEARCH FOR FIRST OCCURRENCE OF N IN SEQUENCE
INTERNAL FUNCTION(N)
ENTRY TO FIRST.
THROUGH SCAN, FOR K = 1, 1, I .G. 1200
SCAN WHENEVER N .E. STERN(K), FUNCTION RETURN K
END OF FUNCTION
END OF PROGRAM</syntaxhighlight>
 
{{out}}
 
<pre style="height: 45ex;">FIRST 15 NUMBERS ARE
1
1
2
1
3
2
3
1
4
3
5
2
5
3
4
FIRST 1 APPEARS AT 1
FIRST 2 APPEARS AT 3
FIRST 3 APPEARS AT 5
FIRST 4 APPEARS AT 9
FIRST 5 APPEARS AT 11
FIRST 6 APPEARS AT 33
FIRST 7 APPEARS AT 19
FIRST 8 APPEARS AT 21
FIRST 9 APPEARS AT 35
FIRST 10 APPEARS AT 39
FIRST 100 APPEARS AT 1179</pre>
 
=={{header|Mathematica}} / {{header|Wolfram Language}}==
<syntaxhighlight lang="mathematica">sb = {1, 1};
Do[
sb = sb~Join~{Total@sb[[i - 1 ;; i]], sb[[i]]}
,
{i, 2, 1000}
]
Take[sb, 15]
Flatten[FirstPosition[sb, #] & /@ Range[10]]
First@FirstPosition[sb, 100]
AllTrue[Partition[Take[sb, 1000], 2, 1], Apply[GCD] /* EqualTo[1]]</syntaxhighlight>
{{out}}
<pre>{1, 1, 2, 1, 3, 2, 3, 1, 4, 3, 5, 2, 5, 3, 4}
{1, 3, 5, 9, 11, 33, 19, 21, 35, 39}
1179
True</pre>
 
=={{header|Miranda}}==
<syntaxhighlight lang="miranda">main :: [sys_message]
main = [Stdout (lay
["First 15: " ++ show first15,
"Indices of first 1..10: " ++ show idx10,
"Index of first 100: " ++ show idx100,
"The GCDs of the first 1000 pairs are all 1: " ++ show allgcd])]
 
first15 :: [num]
first15 = take 15 stern
 
idx10 :: [num]
idx10 = [find num stern | num<-[1..10]]
 
idx100 :: num
idx100 = find 100 stern
 
allgcd :: bool
allgcd = and [gcd a b = 1 | (a, b) <- take 1000 (zip2 stern (tl stern))]
 
 
|| Stern-Brocot sequence
stern :: [num]
stern = 1 : 1 : concat (map consider (zip2 stern (tl stern)))
where consider (prev,item) = [prev + item, item]
 
|| Supporting functions
gcd :: num->num->num
gcd a 0 = a
gcd a b = gcd b (a mod b)
 
find :: *->[*]->num
find item = find' 1
where find' idx [] = 0
find' idx (a:as) = idx, if a = item
= find' (idx + 1) as, otherwise</syntaxhighlight>
{{out}}
<pre>First 15: [1,1,2,1,3,2,3,1,4,3,5,2,5,3,4]
Indices of first 1..10: [1,3,5,9,11,33,19,21,35,39]
Index of first 100: 1179
The GCDs of the first 1000 pairs are all 1: True</pre>
 
=={{header|Modula-2}}==
<syntaxhighlight lang="modula2">MODULE SternBrocot;
FROM InOut IMPORT WriteString, WriteCard, WriteLn;
 
CONST Amount = 1200;
 
VAR stern: ARRAY [1..Amount] OF CARDINAL;
i: CARDINAL;
PROCEDURE GCD(a,b: CARDINAL): CARDINAL;
VAR c: CARDINAL;
BEGIN
WHILE b # 0 DO
c := a MOD b;
a := b;
b := c;
END;
RETURN a;
END GCD;
 
PROCEDURE Generate;
VAR i: CARDINAL;
BEGIN
stern[1] := 1;
stern[2] := 1;
FOR i := 2 TO Amount DIV 2 DO
stern[i*2 - 1] := stern[i] + stern[i-1];
stern[i*2] := stern[i];
END;
END Generate;
 
PROCEDURE FindFirst(n: CARDINAL): CARDINAL;
VAR i: CARDINAL;
BEGIN
FOR i := 1 TO Amount DO
IF stern[i] = n THEN
RETURN i;
END;
END;
END FindFirst;
 
PROCEDURE ShowFirst(n: CARDINAL);
BEGIN
WriteString("First");
WriteCard(n,4);
WriteString(" at ");
WriteCard(FindFirst(n), 4);
WriteLn;
END ShowFirst;
 
BEGIN
Generate;
WriteString("First 15 numbers:");
FOR i := 1 TO 15 DO
WriteCard(stern[i], 2);
END;
WriteLn;
FOR i := 1 TO 10 DO
ShowFirst(i);
END;
ShowFirst(100);
WriteLn;
FOR i := 2 TO Amount DO
IF GCD(stern[i-1], stern[i]) # 1 THEN
WriteString("GCD of adjacent elements not 1 at: ");
WriteCard(i-1, 4);
WriteLn;
HALT;
END;
END;
WriteString("The GCD of every pair of adjacent elements is 1.");
WriteLn;
END SternBrocot.</syntaxhighlight>
{{out}}
<pre>First 15 numbers: 1 1 2 1 3 2 3 1 4 3 5 2 5 3 4
First 1 at 1
First 2 at 3
First 3 at 5
First 4 at 9
First 5 at 11
First 6 at 33
First 7 at 19
First 8 at 21
First 9 at 35
First 10 at 39
First 100 at 1179
 
The GCD of every pair of adjacent elements is 1.</pre>
 
=={{header|Nim}}==
We use an iterator and store the values in a sequence. To reduce memory usage, we could replace the sequence with a deque and pop the previous value at each round. But it’s no worth to complete the task.
 
<syntaxhighlight lang="nim">import math, strformat, strutils
 
iterator sternBrocot(): (int, int) =
## Yield index and value of the terms of the sequence.
var sequence: seq[int]
sequence.add 1
sequence.add 1
var index = 1
yield (1, 1)
yield (2, 1)
while true:
sequence.add sequence[index] + sequence[index - 1]
yield (sequence.len, sequence[^1])
sequence.add sequence[index]
yield (sequence.len, sequence[^1])
inc index
 
# Fiind first 15 terms.
var res: seq[int]
for i, n in sternBrocot():
res.add n
if i == 15: break
echo "First 15 terms: ", res.join(" ")
echo()
 
# Find indexes for 1..10.
var indexes: array[1..10, int]
var toFind = 10
for i, n in sternBrocot():
if n in 1..10 and indexes[n] == 0:
indexes[n] = i
dec toFind
if toFind == 0: break
for n in 1..10:
echo &"Index of first occurrence of number {n:3}: {indexes[n]:4}"
 
# Find index for 100.
var index: int
for i, n in sternBrocot():
if n == 100:
index = i
break
echo &"Index of first occurrence of number 100: {index:4}"
echo()
 
# Check GCD.
var prev = 1
index = 1
for i, n in sternBrocot():
if gcd(prev, n) != 1: break
prev = n
inc index
if index > 1000: break
if index <= 1000:
echo "Found two successive terms at index: ", index
else:
echo "All consecutive terms up to the 1000th member have a GCD equal to one."</syntaxhighlight>
 
{{out}}
<pre>First 15 terms: 1 1 2 1 3 2 3 1 4 3 5 2 5 3 4
 
Index of first occurrence of number 1: 1
Index of first occurrence of number 2: 3
Index of first occurrence of number 3: 5
Index of first occurrence of number 4: 9
Index of first occurrence of number 5: 11
Index of first occurrence of number 6: 33
Index of first occurrence of number 7: 19
Index of first occurrence of number 8: 21
Index of first occurrence of number 9: 35
Index of first occurrence of number 10: 39
Index of first occurrence of number 100: 1179
 
All consecutive terms up to the 1000th member have a GCD equal to one.</pre>
 
=={{header|OCaml}}==
<syntaxhighlight lang="ocaml">let seq_stern_brocot =
let rec next x xs () =
match xs () with
| Seq.Nil -> assert false
| Cons (x', xs') -> Seq.Cons (x' + x, Seq.cons x' (next x' xs'))
in
let rec tail () = Seq.Cons (1, next 1 tail) in
Seq.cons 1 tail</syntaxhighlight>
;<nowiki>Tests:</nowiki>
<syntaxhighlight lang="ocaml">let rec gcd a = function
| 0 -> a
| b -> gcd b (a mod b)
 
let seq_index_of el =
let rec next i sq =
match sq () with
| Seq.Nil -> 0
| Cons (e, sq') -> if e = el then i else next (succ i) sq'
in
next 1
 
let seq_map_pairwise f sq =
match sq () with
| Seq.Nil -> Seq.empty
| Cons (_, sq') -> Seq.map2 f sq sq'
 
let () =
seq_stern_brocot |> Seq.take 15 |> Seq.iter (Printf.printf " %u") |> print_newline
and () =
List.iter
(fun n -> seq_stern_brocot |> seq_index_of n |> Printf.printf " %u@%u" n)
[1; 2; 3; 4; 5; 6; 7; 8; 9; 10; 100]
|> print_newline
and () =
seq_stern_brocot |> Seq.take 1000 |> seq_map_pairwise gcd |> Seq.for_all ((=) 1)
|> Printf.printf " %B\n"</syntaxhighlight>
{{out}}
<pre>
1 1 2 1 3 2 3 1 4 3 5 2 5 3 4
1@1 2@3 3@5 4@9 5@11 6@33 7@19 8@21 9@35 10@39 100@1179
true
</pre>
 
=={{header|Oforth}}==
<syntaxhighlight lang="oforth">: stern(n)
| l i |
ListBuffer new dup add(1) dup add(1) dup ->l
Line 3,068 ⟶ 4,586:
n 2 mod ifFalse: [ dup removeLast drop ] dup freeze ;
 
stern(10000) Constant new: Sterns</langsyntaxhighlight>
 
{{out}}
Line 3,099 ⟶ 4,617:
{{Works with|PARI/GP|2.7.4 and above}}
 
<langsyntaxhighlight lang="parigp">
\\ Stern-Brocot sequence
\\ 5/27/16 aev
Line 3,127 ⟶ 4,645:
if(j==1, print("Yes"), print("No"));
}
</langsyntaxhighlight>
{{Output}}
Line 3,139 ⟶ 4,657:
=={{header|Pascal}}==
{{works with|Free Pascal}}
<langsyntaxhighlight lang="pascal">program StrnBrCt;
{$IFDEF FPC}
{$MODE DELPHI}
Line 3,225 ⟶ 4,743:
writeln('GCD-test is O.K.');
setlength(seq,0);
end.</langsyntaxhighlight>{{Out}}<pre>1,1,2,1,3,2,3,1,4,3,5,2,5,3,4
1 @ 1,2 @ 3,3 @ 5,4 @ 9,5 @ 11,6 @ 33,7 @ 38,8 @ 42,9 @ 47,10 @ 57
100 @ 1179
Line 3,231 ⟶ 4,749:
 
=={{header|Perl}}==
<langsyntaxhighlight lang="perl">use strict;
use warnings;
 
Line 3,266 ⟶ 4,784:
($a, $b) = ($b, $generator->());
}
}</langsyntaxhighlight>
{{out}}
<pre>1 1 2 1 3 2 3 1 4 3 5 2 5 3 4
Line 3,282 ⟶ 4,800:
 
A slightly different method:{{libheader|ntheory}}
<langsyntaxhighlight lang="perl">use ntheory qw/gcd vecsum vecfirst/;
 
sub stern_diatomic {
Line 3,300 ⟶ 4,818:
print "The first 999 consecutive pairs are ",
(vecsum( map { gcd(stern_diatomic($_),stern_diatomic($_+1)) } 1..999 ) == 999)
? "all coprime.\n" : "NOT all coprime!\n";</langsyntaxhighlight>
{{out}}
<pre>First fifteen: [1 1 2 1 3 2 3 1 4 3 5 2 5 3 4]
Line 3,308 ⟶ 4,826:
 
=={{header|Phix}}==
<!--<syntaxhighlight lang="phix">(phixonline)-->
<lang Phix>sequence sb = {1,1}
<span style="color: #004080;">sequence</span> <span style="color: #000000;">sb</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #000000;">1</span><span style="color: #0000FF;">}</span>
integer c = 2
<span style="color: #004080;">integer</span> <span style="color: #000000;">c</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">2</span>
 
function stern_brocot(integer n)
<span style="color: #008080;">function</span> <span style="color: #000000;">stern_brocot</span><span style="color: #0000FF;">(</span><span style="color: #004080;">integer</span> <span style="color: #000000;">n</span><span style="color: #0000FF;">)</span>
while length(sb)<n do
<span style="color: #008080;">while</span> <span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">sb</span><span style="color: #0000FF;">)<</span><span style="color: #000000;">n</span> <span style="color: #008080;">do</span>
sb &= sb[c]+sb[c-1] & sb[c]
<span style="color: #000000;">sb</span> <span style="color: #0000FF;">&=</span> <span style="color: #000000;">sb</span><span style="color: #0000FF;">[</span><span style="color: #000000;">c</span><span style="color: #0000FF;">]+</span><span style="color: #000000;">sb</span><span style="color: #0000FF;">[</span><span style="color: #000000;">c</span><span style="color: #0000FF;">-</span><span style="color: #000000;">1</span><span style="color: #0000FF;">]</span> <span style="color: #0000FF;">&</span> <span style="color: #000000;">sb</span><span style="color: #0000FF;">[</span><span style="color: #000000;">c</span><span style="color: #0000FF;">]</span>
c += 1
<span style="color: #000000;">c</span> <span style="color: #0000FF;">+=</span> <span style="color: #000000;">1</span>
end while
<span style="color: #008080;">end</span> <span style="color: #008080;">while</span>
return sb[1..n]
<span style="color: #008080;">return</span> <span style="color: #000000;">sb</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>
end function
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
 
sequence s = stern_brocot(15)
<span style="color: #004080;">sequence</span> <span style="color: #000000;">s</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">stern_brocot</span><span style="color: #0000FF;">(</span><span style="color: #000000;">15</span><span style="color: #0000FF;">)</span>
puts(1,"first 15:")
<span style="color: #7060A8;">puts</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"first 15:"</span><span style="color: #0000FF;">)</span>
?s
<span style="color: #0000FF;">?</span><span style="color: #000000;">s</span>
integer n = 16, k
<span style="color: #004080;">integer</span> <span style="color: #000000;">n</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">16</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">k</span>
sequence idx = tagset(10)
<span style="color: #004080;">sequence</span> <span style="color: #000000;">idx</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">tagset</span><span style="color: #0000FF;">(</span><span style="color: #000000;">10</span><span style="color: #0000FF;">)</span>
for i=1 to length(idx) do
<span style="color: #008080;">for</span> <span style="color: #000000;">i</span><span style="color: #0000FF;">=</span><span style="color: #000000;">1</span> <span style="color: #008080;">to</span> <span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">idx</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">do</span>
while 1 do
<span style="color: #008080;">while</span> <span style="color: #000000;">1</span> <span style="color: #008080;">do</span>
k = find(idx[i],s)
<span style="color: #000000;">k</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">find</span><span style="color: #0000FF;">(</span><span style="color: #000000;">idx</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">],</span><span style="color: #000000;">s</span><span style="color: #0000FF;">)</span>
if k!=0 then exit end if
<span style="color: #008080;">if</span> <span style="color: #000000;">k</span><span style="color: #0000FF;">!=</span><span style="color: #000000;">0</span> <span style="color: #008080;">then</span> <span style="color: #008080;">exit</span> <span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
n *= 2
<span style="color: #000000;">n</span> <span style="color: #0000FF;">*=</span> <span style="color: #000000;">2</span>
s = stern_brocot(n)
<span style="color: #000000;">s</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">stern_brocot</span><span style="color: #0000FF;">(</span><span style="color: #000000;">n</span><span style="color: #0000FF;">)</span>
end while
<span style="color: #008080;">end</span> <span style="color: #008080;">while</span>
idx[i] = k
<span style="color: #000000;">idx</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">]</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">k</span>
end for
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
puts(1,"indexes of 1..10:")
<span style="color: #7060A8;">puts</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"indexes of 1..10:"</span><span style="color: #0000FF;">)</span>
?idx
<span style="color: #0000FF;">?</span><span style="color: #000000;">idx</span>
puts(1,"index of 100:")
<span style="color: #7060A8;">puts</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"index of 100:"</span><span style="color: #0000FF;">)</span>
while 1 do
<span style="color: #008080;">while</span> <span style="color: #000000;">1</span> <span style="color: #008080;">do</span>
k = find(100,s)
<span style="color: #000000;">k</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">find</span><span style="color: #0000FF;">(</span><span style="color: #000000;">100</span><span style="color: #0000FF;">,</span><span style="color: #000000;">s</span><span style="color: #0000FF;">)</span>
if k!=0 then exit end if
<span style="color: #008080;">if</span> <span style="color: #000000;">k</span><span style="color: #0000FF;">!=</span><span style="color: #000000;">0</span> <span style="color: #008080;">then</span> <span style="color: #008080;">exit</span> <span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
n *= 2
<span style="color: #000000;">n</span> <span style="color: #0000FF;">*=</span> <span style="color: #000000;">2</span>
s = stern_brocot(n)
<span style="color: #000000;">s</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">stern_brocot</span><span style="color: #0000FF;">(</span><span style="color: #000000;">n</span><span style="color: #0000FF;">)</span>
end while
<span style="color: #008080;">end</span> <span style="color: #008080;">while</span>
?k
<span style="color: #0000FF;">?</span><span style="color: #000000;">k</span>
s = stern_brocot(1000)
<span style="color: #000000;">s</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">stern_brocot</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1000</span><span style="color: #0000FF;">)</span>
integer maxgcd = 1
<span style="color: #004080;">integer</span> <span style="color: #000000;">maxgcd</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">1</span>
for i=1 to 999 do
<span style="color: #008080;">for</span> <span style="color: #000000;">i</span><span style="color: #0000FF;">=</span><span style="color: #000000;">1</span> <span style="color: #008080;">to</span> <span style="color: #000000;">999</span> <span style="color: #008080;">do</span>
maxgcd = max(gcd(s[i],s[i+1]),maxgcd)
<span style="color: #000000;">maxgcd</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">max</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">gcd</span><span style="color: #0000FF;">(</span><span style="color: #000000;">s</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">],</span><span style="color: #000000;">s</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">+</span><span style="color: #000000;">1</span><span style="color: #0000FF;">]),</span><span style="color: #000000;">maxgcd</span><span style="color: #0000FF;">)</span>
end for
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
printf(1,"max gcd:%d\n",{maxgcd})</lang>
<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;">"max gcd:%d\n"</span><span style="color: #0000FF;">,{</span><span style="color: #000000;">maxgcd</span><span style="color: #0000FF;">})</span>
<!--</syntaxhighlight>-->
{{Out}}
<pre>
Line 3,360 ⟶ 4,880:
{{trans|C}}
Using the <tt>gcd</tt> function defined at ''[[Greatest_common_divisor#PicoLisp]]'':
<langsyntaxhighlight PicoLisplang="picolisp">(de nmbr (N)
(let (A 1 B 0)
(while (gt0 N)
Line 3,376 ⟶ 4,896:
(for (L Lst (cdr L) (cddr L))
(test 1 (gcd (car L) (cadr L))) )
(prinl "All consecutive pairs are relative prime!") )</langsyntaxhighlight>
{{out}}
<pre>
Line 3,393 ⟶ 4,913:
All consecutive pairs are relative prime!
</pre>
 
=={{header|PL/I}}==
<syntaxhighlight lang="pli">sternBrocot: procedure options(main);
%replace MAX by 1200;
declare S(1:MAX) fixed;
/* find the first occurrence of N in S */
findFirst: procedure(n) returns(fixed);
declare (n, i) fixed;
do i=1 to MAX;
if S(i)=n then return(i);
end;
end findFirst;
/* find the greatest common divisor of A and B */
gcd: procedure(a, b) returns(fixed) recursive;
declare (a, b) fixed;
if b = 0 then return(a);
return(gcd(b, mod(a, b)));
end gcd;
/* calculate S(i) up to MAX */
declare i fixed;
S(1) = 1; S(2) = 1;
do i=2 to MAX/2;
S(i*2-1) = S(i) + S(i-1);
S(i*2) = S(i);
end;
/* print first 15 elements */
put skip list('First 15 elements: ');
do i=1 to 15;
put edit(S(i)) (F(2));
end;
/* find first occurrences of 1..10 and 100 */
do i=1 to 10;
put skip list('First',i,'at',findFirst(i));
end;
put skip list('First ',100,'at',findFirst(100));
/* check GCDs of adjacent pairs up to 1000th element */
do i=2 to 1000;
if gcd(S(i-1),S(i)) ^= 1 then do;
put skip list('GCD of adjacent pair not 1 at i=',i);
stop;
end;
end;
put skip list('All GCDs of adjacent pairs are 1.');
end sternBrocot;</syntaxhighlight>
{{out}}
<pre>First 15 elements: 1 1 2 1 3 2 3 1 4 3 5 2 5 3 4
First 1 at 1
First 2 at 3
First 3 at 5
First 4 at 9
First 5 at 11
First 6 at 33
First 7 at 19
First 8 at 21
First 9 at 35
First 10 at 39
First 100 at 1179
All GCDs of adjacent pairs are 1.</pre>
 
=={{header|PL/M}}==
<syntaxhighlight lang="plm">100H:
/* FIND LOCATION OF FIRST ELEMENT IN ARRAY */
FIND$FIRST: PROCEDURE (ARR, EL) ADDRESS;
DECLARE (ARR, N) ADDRESS, (EL, A BASED ARR) BYTE;
N = 0;
LOOP:
IF A(N) = EL THEN RETURN N;
ELSE N = N + 1;
GO TO LOOP;
END FIND$FIRST;
 
/* CP/M CALL */
BDOS: PROCEDURE (FN, ARG);
DECLARE FN BYTE, ARG ADDRESS;
GO TO 5;
END BDOS;
 
PRINT: PROCEDURE (STRING);
DECLARE STRING ADDRESS;
CALL BDOS(9, STRING);
END PRINT;
 
/* PRINT NUMBER */
PRINT$NUMBER: PROCEDURE (N);
DECLARE S (6) BYTE INITIAL ('.....$');
DECLARE (N, P) ADDRESS, C BASED P BYTE;
P = .S(5);
DIGIT:
P = P - 1;
C = N MOD 10 + '0';
IF (N := N / 10) > 0 THEN GO TO DIGIT;
CALL PRINT(P);
END PRINT$NUMBER;
 
/* GENERATE FIRST 1200 ELEMENTS OF STERN-BROCOT SEQUENCE */
DECLARE S (1201) BYTE, I ADDRESS;
S(1) = 1;
S(2) = 1;
DO I = 2 TO 600;
S(I*2-1) = S(I) + S(I-1);
S(I*2) = S(I);
END;
 
/* PRINT FIRST 15 ELEMENTS */
CALL PRINT(.'FIRST 15 ELEMENTS: $');
DO I = 1 TO 15;
CALL PRINT$NUMBER(S(I));
CALL PRINT(.' $');
END;
CALL PRINT(.(13,10,'$'));
 
/* PRINT FIRST OCCURRENCE OF N */
PRINT$FIRST: PROCEDURE (N);
DECLARE N BYTE;
CALL PRINT(.'FIRST $');
CALL PRINT$NUMBER(N);
CALL PRINT(.' AT $');
CALL PRINT$NUMBER(FIND$FIRST(.S, N));
CALL PRINT(.(13,10,'$'));
END PRINT$FIRST;
 
DO I = 1 TO 10;
CALL PRINT$FIRST(I);
END;
CALL PRINT$FIRST(100);
 
/* CHECK GCDS */
GCD: PROCEDURE (A, B) BYTE;
DECLARE (A, B, C) BYTE;
LOOP:
C = A;
A = B;
B = C MOD A;
IF B <> 0 THEN GO TO LOOP;
RETURN A;
END GCD;
 
DO I = 2 TO 1000;
IF GCD(S(I-1),S(I)) <> 1 THEN DO;
CALL PRINT(.'GCD NOT 1 AT: $');
CALL PRINT$NUMBER(I);
CALL BDOS(0,0);
END;
END;
 
CALL PRINT(.'ALL GCDS ARE 1$');
CALL BDOS(0,0);
EOF</syntaxhighlight>
{{out}}
<pre>FIRST 15 ELEMENTS: 1 1 2 1 3 2 3 1 4 3 5 2 5 3 4
FIRST 1 AT 1
FIRST 2 AT 3
FIRST 3 AT 5
FIRST 4 AT 9
FIRST 5 AT 11
FIRST 6 AT 33
FIRST 7 AT 19
FIRST 8 AT 21
FIRST 9 AT 35
FIRST 10 AT 39
FIRST 100 AT 1179
ALL GCDS ARE 1</pre>
 
=={{header|PowerShell}}==
<syntaxhighlight lang="powershell">
<lang PowerShell>
# An iterative approach
function iter_sb($count = 2000)
Line 3,424 ⟶ 5,112:
'GCD = 1 for first 1000 members: {0}' -f $gcd
}
</syntaxhighlight>
</lang>
 
{{out}}
Line 3,457 ⟶ 5,145:
GCD = 1 for first 1000 members: True
</pre>
 
=={{header|PureBasic}}==
<syntaxhighlight lang="purebasic">EnableExplicit
Define.i i
 
If OpenConsole("")
PrintN("Stern-Brocot_sequence")
Else
End 1
EndIf
 
Procedure.i f(n.i)
If n<2
ProcedureReturn n
ElseIf n&1
ProcedureReturn f(n/2)+f(n/2+1)
Else
ProcedureReturn f(n/2)
EndIf
EndProcedure
 
Procedure.i gcd(a.i,b.i)
If b : ProcedureReturn gcd(b,a%b) : EndIf
ProcedureReturn a
EndProcedure
 
Procedure.i ind(m.i)
Define.i i=1
While f(i)<>m : i+1 : Wend
ProcedureReturn i
EndProcedure
 
Print("First 15 elements: ")
For i=1 To 15
Print(Str(f(i))+Space(3))
Next
PrintN(~"\n")
 
For i=1 To 10
PrintN(RSet(Str(i),3)+" is at pos. #"+Str(ind(i)))
Next
PrintN("100 is at pos. #"+Str(ind(100)))
PrintN("")
 
i=1
While i<1000 And gcd(f(i),f(i+1))=1 : i+1 : Wend
If i=1000
PrintN("All GCDs are 1.")
Else
PrintN("GCD of "+Str(i)+" and "+Str(i+1)+" is not 1")
EndIf
 
Input()</syntaxhighlight>
{{out}}
<pre>Stern-Brocot_sequence
First 15 elements: 1 1 2 1 3 2 3 1 4 3 5 2 5 3 4
 
1 is at pos. #1
2 is at pos. #3
3 is at pos. #5
4 is at pos. #9
5 is at pos. #11
6 is at pos. #33
7 is at pos. #19
8 is at pos. #21
9 is at pos. #35
10 is at pos. #39
100 is at pos. #1179
 
All GCDs are 1.</pre>
 
=={{header|Python}}==
===Python: procedural===
<langsyntaxhighlight lang="python">def stern_brocot(predicate=lambda series: len(series) < 20):
"""\
Generates members of the stern-brocot series, in order, returning them when the predicate becomes false
Line 3,495 ⟶ 5,253:
s = stern_brocot(lambda series: len(series) < n_gcd)[:n_gcd]
assert all(gcd(prev, this) == 1
for prev, this in zip(s, s[1:])), 'A fraction from adjacent terms is reducible'</langsyntaxhighlight>
 
{{out}}
Line 3,518 ⟶ 5,276:
 
See the [[Talk:Stern-Brocot_sequence#deque_over_list.3F|talk page]] for how a deque was selected over the use of a straightforward list'
<langsyntaxhighlight lang="python">>>> from itertools import takewhile, tee, islice
>>> from collections import deque
>>> from fractions import gcd
Line 3,539 ⟶ 5,297:
>>> all(gcd(p, t) == 1 for p, t in islice(zip(prev, this), 1000))
True
>>> </langsyntaxhighlight>
 
===Python: Composing pure (curried) functions===
Line 3,545 ⟶ 5,303:
Composing and testing a Stern-Brocot function by composition of generic and reusable functional abstractions (curried for more flexible nesting and rearrangement).
{{Works with|Python|3.7}}
<langsyntaxhighlight lang="python">'''Stern-Brocot sequence'''
 
import math
from itertools import (count, dropwhile, islice, takewhile)
import operator
from itertools import count, dropwhile, islice, takewhile
import math
 
 
Line 3,555 ⟶ 5,313:
def sternBrocot():
'''Non-finite list of the Stern-Brocot
sequence of integers.'''
'''
 
def go(xs):
x[a, b] = xs[1:2]
return (tail(a, xs)[1:] + [xa + head(xs)b, xb])
return fmapGenunfoldr(headgo)([1, 1])
iterate(go)([1, 1])
)
 
 
# TESTS ---------------------------------------------------
 
# ------------------------ TESTS -------------------------
# main :: IO ()
def main():
Line 3,608 ⟶ 5,363:
 
 
# GENERIC ABSTRACTIONS ------------------- GENERIC ABSTRACTIONS -----------------
 
 
# compose (<<<) :: (b -> c) -> (a -> b) -> a -> c
Line 3,637 ⟶ 5,391:
'''True if p(x) holds for every x in xs'''
return lambda xs: all(map(p, xs))
 
 
# fmapGen <$> :: (a -> b) -> Gen [a] -> Gen [b]
def fmapGen(f):
'''A function f mapped over a
non finite stream of values.'''
def go(g):
while True:
v = next(g, None)
if None is not v:
yield f(v)
else:
return
return lambda gen: go(gen)
 
 
Line 3,663 ⟶ 5,403:
'''The first element of a non-empty list.'''
return xs[0]
 
 
# iterate :: (a -> a) -> a -> Gen [a]
def iterate(f):
'''An infinite list of repeated
applications of f to x.'''
def go(x):
v = x
while True:
yield v
v = f(v)
return lambda x: go(x)
 
 
Line 3,681 ⟶ 5,409:
'''A sublist of xs from which all duplicates,
(as defined by the equality predicate p)
are excluded.'''
'''
def go(xs):
if not xs:
Line 3,692 ⟶ 5,421:
))
)
return lambda xs: go(xs)
 
 
Line 3,710 ⟶ 5,439:
return xs[1:]
else:
list(islice(xs, 1)) # First item dropped.
return xs
 
Line 3,724 ⟶ 5,453:
else list(islice(xs, n))
)
 
 
# unfoldr :: (b -> Maybe (a, b)) -> b -> Gen [a]
def unfoldr(f):
'''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 list, wrap the result with list()
'''
def go(x):
valueResidue = f(x)
while valueResidue:
yield valueResidue[0]
valueResidue = f(valueResidue[1])
return go
 
 
Line 3,735 ⟶ 5,480:
# MAIN ---
if __name__ == '__main__':
main()</langsyntaxhighlight>
{{Out}}
<pre>[1, 1, 2, 1, 3, 2, 3, 1, 4, 3, 5, 2, 5, 3, 4]
Line 3,741 ⟶ 5,486:
[(100, 1179)]
True</pre>
 
=={{header|Quackery}}==
<syntaxhighlight lang="quackery"> [ [ dup while
tuck mod again ]
drop abs ] is gcd ( n n --> n )
 
[ 2dup peek
dip [ 1+ 2dup peek ]
over + swap join
swap dip join ] is two-terms ( [ n --> [ n )
 
' [ 1 1 ] 0
8 times two-terms
over 15 split drop
witheach [ echo sp ] cr
[ two-terms
over -2 peek 100 = until ]
drop
10 times
[ i^ 1+ over find 1+ echo sp ] cr
dup size 1 - echo cr
false swap
behead swap witheach
[ tuck gcd 1 != if
[ dip not conclude ] ]
drop iff
[ say "Reducible pair found." ]
else
[ say "No reducible pairs found." ]</syntaxhighlight>
 
{{out}}
 
<pre>1 1 2 1 3 2 3 1 4 3 5 2 5 3 4
1 3 5 9 11 33 19 21 35 39
1179
No reducible pairs found.
</pre>
 
=={{header|R}}==
Line 3,748 ⟶ 5,530:
{{libheader|pracma}}
 
<syntaxhighlight lang="rsplus">
<lang r>
## Stern-Brocot sequence
## 12/19/16 aev
Line 3,771 ⟶ 5,553:
if(j==1) {cat(" *** All GCDs=1!\n")} else {cat(" *** All GCDs!=1??\n")}
}
</langsyntaxhighlight>
 
{{Output}}
Line 3,789 ⟶ 5,571:
 
As with the previous solution, we have used a library for our gcd function. In this case, we have used gmp.
<langsyntaxhighlight rlang="rsplus">genNStern <- function(n)
{
sternNums <- c(1L1,1L 1)
i <- 2
while((endIndex <- length(sternNums)) < n)
{
#To show off R's vectorization, the following line is deliberately terse.
Line 3,800 ⟶ 5,582:
#Note that we do not have to initialize a big sternNums array to do this.
#True to the algorithm, the new entries are appended to the end of the old sequence.
sternNums[endIndex + c(1, 2)] <- c(sum(sternNums[c(i - 1, i)]), sternNums[i])
i <- i + 1
}
sternNums[1:seq_len(n)]
}
#N=5000 was picked arbitrarily. The code runs very fast regardless of this number being much more than we need.
firstFiveThousandTerms <- genNStern(5000)
match(1:10, firstFiveThousandTerms)
match(100, firstFiveThousandTerms)
all(sapply(1:999, function(i) gmp::gcd(firstFiveThousandTerms[i], firstFiveThousandTerms[i + 1])) == 1)</langsyntaxhighlight>
{{Output}}
<pre>> firstFiveThousandTerms <- genNStern(5000)
> match(1:10, firstFiveThousandTerms)
[1] 1 3 5 9 11 33 19 21 35 39
> match(100, firstFiveThousandTerms)
[1] 1179
> all(sapply(1:999, function(i) gmp::gcd(firstFiveThousandTerms[i], firstFiveThousandTerms[i + 1])) == 1)
[1] TRUE</pre>
 
=={{header|Racket}}==
<syntaxhighlight lang="racket">#lang racket
 
<lang racket>#lang racket
;; OEIS Definition
;; A002487
Line 3,858 ⟶ 5,639:
(for/first ((i (in-range 1 1000))
#:unless (= 1 (gcd (Stern-Brocot i) (Stern-Brocot (add1 i))))) #t)
(display "\tdidn't find gcd > (or otherwise ≠) 1"))</langsyntaxhighlight>
 
{{out}}
Line 3,884 ⟶ 5,665:
(formerly Perl 6)
{{works with|rakudo|2017-03}}
<syntaxhighlight lang="raku" perl6line>constant @Stern-Brocot = 1, 1, { |(@_[$_ - 1] + @_[$_], @_[$_]) given ++$ } ... *;
|(@_[$_ - 1] + @_[$_], @_[$_]) given ++$
} ... *;
 
sayput @Stern-Brocot[^15];
 
for (flat 1..10, 100) -> $ix {
say "firstFirst occurrence of {$ix.fmt('%3d')} is at index : ", {(1 + @Stern-Brocot.first($ix, :k)).fmt('%4d')}";
}
 
say so 1 == all map ^1000: { [gcd] @Stern-Brocot[$_, $_ + 1] }</langsyntaxhighlight>
{{out}}
<pre>1 1 2 1 3 2 3 1 4 3 5 2 5 3 4
firstFirst occurrence of 1 is at index : 1
firstFirst occurrence of 2 is at index : 3
firstFirst occurrence of 3 is at index : 5
firstFirst occurrence of 4 is at index : 9
firstFirst occurrence of 5 is at index : 11
firstFirst occurrence of 6 is at index : 33
firstFirst occurrence of 7 is at index : 19
firstFirst occurrence of 8 is at index : 21
firstFirst occurrence of 9 is at index : 35
firstFirst occurrence of 10 is at index : 39
firstFirst occurrence of 100 is at index : 1179
True</pre>
 
=={{header|Refal}}==
<syntaxhighlight lang="refal">$ENTRY Go {
, <Stern 1300>: e.Seq
= <Prout 'First 15: ' <Take 15 e.Seq>>
<ForEach (<Iota 1 10>) ShowFirst e.Seq>
<ShowFirst 100 e.Seq>
<Prout <GcdPairCheck <Take 1000 e.Seq>>>;
};
 
Stern {
s.N = <Stern <- s.N 2> (1) 1>;
0 (e.X) e.Y = e.X e.Y;
s.N (e.X s.P) s.C e.Y,
<- s.N 1>: s.Rem,
<+ s.P s.C>: s.CSum
= <Stern s.Rem (e.X s.P s.C) e.Y s.CSum s.C>;
};
 
Take {
0 e.X = ;
s.N s.I e.X = s.I <Take <- s.N 1> e.X>;
};
 
FindFirst {
s.I e.X = <FindFirst (1) s.I e.X>;
(s.L) s.I s.I e.X = s.L;
(s.L) s.I s.J e.X = <FindFirst (<+ s.L 1>) s.I e.X>;
};
 
ShowFirst {
s.I e.X, <FindFirst s.I e.X>: s.N = <Prout 'First ' s.I 'at ' s.N>;
};
 
ForEach {
() s.F e.Arg = ;
(s.I e.X) s.F e.Arg = <Mu s.F s.I e.Arg> <ForEach (e.X) s.F e.Arg>;
};
 
Iota {
s.From s.To = <Iota s.From s.To s.From>;
s.From s.To s.To = s.To;
s.From s.To s.Cur = s.Cur <Iota s.From s.To <+ s.Cur 1>>;
};
 
Gcd {
s.N 0 = s.N;
s.N s.M = <Gcd s.M <Mod s.N s.M>>;
};
 
GcdPairCheck {
s.A s.B e.X, <Gcd s.A s.B>: 1
= <GcdPairCheck s.B e.X>;
s.A s.B e.X, <Gcd s.A s.B>: s.N
= 'The GCD of ' <Symb s.A> ' and ' <Symb s.B> ' is ' <Symb s.N>;
e.X = 'The GCDs of all adjacent pairs are 1.';
};</syntaxhighlight>
{{out}}
<pre>First 15: 1 1 2 1 3 2 3 1 4 3 5 2 5 3 4
First 1 at 1
First 2 at 3
First 3 at 5
First 4 at 9
First 5 at 11
First 6 at 33
First 7 at 19
First 8 at 21
First 9 at 35
First 10 at 39
First 100 at 1179
The GCDs of all adjacent pairs are 1.</pre>
=={{header|REXX}}==
<langsyntaxhighlight lang="rexx">/*REXX program generates & displays a Stern─Brocot sequence; finds 1─based indices; GCDs*/
parse arg N idx fix chk . /*get optional arguments from the C.L. */
if N=='' | N=="," then N= 15 15 /*Not specified? Then use the default.*/
if idx=='' | idx=="," then idx= 10 10 /* " " " " " " */
if fix=='' | fix=="," then fix= 100 100 /* " " " " " " */
if chk=='' | chk=="," then chk=1000 1000 /* " " " " " " */
 
if N>0 then say center('the first' N "numbers in the Stern─Brocot sequence", 70, '═')
a= Stern_Brocot(N) /*invoke function to generate sequence.*/
say a /*display the sequence to the terminal.*/
say
say center('the 1─based index for the first' idx "integers", 70, '═')
a= Stern_Brocot(-idx) /*invoke function to generate sequence.*/
w= length(idx); do i=1 for idx
say 'for ' right(i, w)", the index is: " wordpos(i, a)
end /*i*/
say
say center('the 1─based index for' fix, 70, "═")
a= Stern_Brocot(-fix) /*invoke function to generate sequence.*/
say 'for ' fix", the index is: " wordpos(fix, a)
say
if chk<2 then exit 0
say center('checking if all two consecutive members have a GCD=1', 70, '═')
a= Stern_Brocot(chk) /*invoke function to generate sequence.*/
do c=1 for chk-1; if gcd(subword(a, c, 2))==1 then iterate
say 'GCD check failed at index' c; exit 13
end /*c*/
say
 
say '───── All ' chk " two consecutive members have a GCD of unity."
exit 0 /*stick a fork in it, we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
gcd: procedure; $=; do i=1 for arg(); $= $ arg(i) /*get arg list. */
end /*i*/
parse var $ x z .; if x=0 then x=z z /*is zero case? */
x=abs(x) /*use absolute x*/
do j=2 to words($); y=abs( word($, j) )
Line 3,952 ⟶ 5,802:
return x /*return the GCD*/
/*──────────────────────────────────────────────────────────────────────────────────────*/
Stern_Brocot: parse arg h 1 f; $= 1 1; if h<0 then h= 1e9
else f= 0
f= abs(f)
do k=2 until words($)>=h | wordpos(f, $)\==0; _=word($, k)
_= word($, k); $= $ (_ + word($, k-1) ) _
end /*k*/
if f==0 then return subword($, 1, h)
return $</langsyntaxhighlight>
{{out|output|text=&nbsp; when using the default inputs:}}
<pre>
Line 3,985 ⟶ 5,835:
 
=={{header|Ring}}==
<langsyntaxhighlight lang="ring">
# Project : Stern-Brocot sequence
 
Line 4,039 ⟶ 5,889:
end
return gcd
</syntaxhighlight>
</lang>
Output:
<pre>
Line 4,056 ⟶ 5,906:
Correct: The first 999 consecutive pairs are relative prime!
</pre>
 
=={{header|RPL}}==
Task 1 is done by applying the algorithm explained above.
Other requirements are based on Mike Stay's formula for OEIS AA002487:
a(n) = a(n-2) + a(n-1) - 2*(a(n-2) mod a(n-1))
which avoids keeping a huge subset of the sequence in memory
{{works with|Halcyon Calc|4.2.7}}
{| class="wikitable"
! RPL code
! Comment
|-
|
{ 1 1 } 1
'''WHILE''' OVER SIZE 4 PICK < '''REPEAT'''
GETI ROT ROT DUP2 GET 4 ROLL +
ROT SWAP + SWAP
DUP2 GET ROT SWAP + SWAP
'''END''' ROT DROP2
≫ ‘'''TASK1'''’ STO
0 1
2 4 ROLL '''START'''
DUP2 + LAST MOD 2 * - ROT DROP '''NEXT'''
SWAP DROP
≫ ‘'''STERN'''’ STO
≪ 1
'''WHILE''' DUP '''STERN''' 3 PICK ≠ '''REPEAT''' 1 + '''END''' R→C
≫ ‘'''WHEN'''’ STO
|
'''TASK1''' ''( n -- {SB(1)..SB(n) )''
initialize stack with SB(1), SB(2) and pointer i
loop until SB(n) reached
get SB(i)+SB(i+1)
add to list
add SB(i+1) to list
clean stack
'''STERN''' ''( n -- SB(n) )''
initialize stack with SB(0), SB(1)
loop n-2 times
SB(i)=SB(i-1)+SB(i-2)-2*(SB(i-2) mod SB(i-1))
clean stack
'''WHEN''' ''( m -- (n,SB(n)) )'' with SB(n) = m
loop until found
|}
{{in}}
<pre>
15 TASK1
{ } 1 10 FOR n n WHEN + NEXT
100 WHEN
</pre>
{{out}}
<pre>
3: { 1 1 2 1 3 2 3 1 4 3 5 2 5 3 4 1 }
2: { (1,1) (2,3) (3,5) (4,9) (5,11) (6,33) (7,19) (8,21) (9,35) (10,39) }
1: (100,1179)
</pre>
===Faster version for big values of n===
We use here the fact that
SB(2^k) = 1 and SB(2^k + 1) = k+1 for any k>0
which can be easily demonstrated by using the definition of the fusc sequence, identical to the Stern-Brocot sequence (OEIS AA002487).
{| class="wikitable"
! RPL code
! Comment
|-
|
'''IF''' DUP 4 < '''THEN''' 0 1
'''ELSE'''
DUP LN 2 LN / IP 2 OVER ^
ROT SWAP - 1 ROT 1 +
'''END'''
≫ ‘'''Offset'''’ STO
'''Offset'''
2 4 ROLL '''START'''
DUP2 + LAST MOD 2 * - ROT DROP '''NEXT'''
SWAP DROP
≫ ‘'''STERN'''’ STO
|
'''Offset''' ''( n -- 1 k+1 offset )''
start at the beginning for small n values
otherwise
get k with 2^k ≤ n
initialize stack to 1, k+1, n-2^k
'''STERN''' ''( n -- SB(n) )''
initialize stack
loop n-2 times
SB(i)=SB(i-1)+SB(i-2)-2*(SB(i-2) mod SB(i-1))
clean stack
|}
2147484950 '''STERN'''
1: 1385
 
=={{header|Ruby}}==
{{works with|Ruby|2.1}}
<langsyntaxhighlight lang="ruby">def sb
return enum_for :sb unless block_given?
a=[1,1]
Line 4,078 ⟶ 6,033:
else
puts "Whoops, not all GCD's are 1!"
end</langsyntaxhighlight>
 
{{out}}
Line 4,098 ⟶ 6,053:
 
=={{header|Scala}}==
<langsyntaxhighlight lang="scala">lazy val sbSeq: Stream[BigInt] = {
BigInt("1") #::
BigInt("1") #::
Line 4,116 ⟶ 6,071:
(sbSeq zip sbSeq.tail).take(1000).forall{ case (a,b) => a.gcd(b) == 1 } )
}
</syntaxhighlight>
</lang>
 
{{out}}
Line 4,137 ⟶ 6,092:
</pre>
 
=={{header|Scheme}}==
{{works with|Chez Scheme}}
'''The Function'''
<syntaxhighlight lang="scheme">; Recursive function to return the Nth Stern-Brocot sequence number.
 
(define stern-brocot
(lambda (n)
(cond
((<= n 0)
0)
((<= n 2)
1)
((even? n)
(stern-brocot (/ n 2)))
(else
(let ((earlier (/ (1+ n) 2)))
(+ (stern-brocot earlier) (stern-brocot (1- earlier))))))))</syntaxhighlight>
'''The Task'''
<syntaxhighlight lang="scheme">; Show the first 15 Stern-Brocot sequence numbers.
 
(printf "First 15 Stern-Brocot numbers:")
(do ((index 1 (1+ index)))
((> index 15))
(printf " ~a" (stern-brocot index)))
(newline)
 
; Show the indices of where the numbers 1 to 10 first appear in the Stern-Brocot sequence.
 
(let ((indices (make-vector 11 #f))
(found 0))
(do ((index 1 (1+ index)))
((>= found 10))
(let ((number (stern-brocot index)))
(when (and (<= number 10) (not (vector-ref indices number)))
(vector-set! indices number index)
(set! found (1+ found)))))
(printf "Indices of where the numbers 1 to 10 first appear:")
(do ((index 1 (1+ index)))
((> index 10))
(printf " ~a" (vector-ref indices index))))
(newline)
 
; Show the index of where the number 100 first appears in the Stern-Brocot sequence.
 
(do ((index 1 (1+ index)) (found #f))
(found)
(let ((number (stern-brocot index)))
(when (= number 100)
(printf "Index where the number 100 first appears: ~a~%" index)
(set! found #t))))
 
; Check that the GCD of all two consecutive members up to the 1000th member is always one.
 
(let ((any-bad #f)
(gcd (lambda (a b)
(if (= b 0)
a
(gcd b (remainder a b))))))
(do ((index 1 (1+ index)))
((> index 1000))
(let ((sbgcd (gcd (stern-brocot index) (stern-brocot (1+ index)))))
(when (not (= 1 sbgcd))
(printf "GCD of Stern-Brocot ~a and ~a+1 is ~a -- Not 1~%" index index sbgcd)
(set! any-bad #t))))
(when (not any-bad)
(printf "GCDs of all Stern-Brocot consecutive pairs from 1 to 1000 are 1~%")))</syntaxhighlight>
{{out}}
<pre>First 15 Stern-Brocot numbers: 1 1 2 1 3 2 3 1 4 3 5 2 5 3 4
Indices of where the numbers 1 to 10 first appear: 1 3 5 9 11 33 19 21 35 39
Index where the number 100 first appears: 1179
GCDs of all Stern-Brocot consecutive pairs from 1 to 1000 are 1</pre>
 
=={{header|SETL}}==
<syntaxhighlight lang="setl">program stern_brocot_sequence;
s := stern(1200);
 
print("First 15 elements:", s(1..15));
 
loop for n in [1..10] with 100 do
if exists k = s(i) | k = n then
print("First", n, "at", i);
end if;
end loop;
 
gcds := [gcd(s(i-1), s(i)) : i in [2..1000]];
 
if exists g = gcds(i) | g /= 1 then
print("The GCD of the pair at", i, "is not 1.");
else
print("All GCDs of consecutive pairs up to 1000 are 1.");
end if;
 
proc stern(n);
s := [1, 1];
loop for i in [2..n div 2] do
s(i*2-1) := s(i) + s(i-1);
s(i*2) := s(i);
end loop;
return s;
end proc;
 
proc gcd(a,b);
loop while b/=0 do
[a, b] := [b, a mod b];
end loop;
return a;
end proc;
end program;</syntaxhighlight>
{{out}}
<pre>First 15 elements: [1 1 2 1 3 2 3 1 4 3 5 2 5 3 4]
First 1 at 1
First 2 at 3
First 3 at 5
First 4 at 9
First 5 at 11
First 6 at 33
First 7 at 19
First 8 at 21
First 9 at 35
First 10 at 39
First 100 at 1179
All GCDs of consecutive pairs up to 1000 are 1.</pre>
=={{header|Sidef}}==
{{trans|Perl}}
<langsyntaxhighlight lang="ruby"># Declare a function to generate the Stern-Brocot sequence
func stern_brocot {
var list = [1, 1]
Line 4,172 ⟶ 6,249:
} * 1000
 
say "All GCD's are 1"</langsyntaxhighlight>
{{out}}
<pre>
Line 4,190 ⟶ 6,267:
</pre>
 
=={{header|SwiftSnobol}}==
<syntaxhighlight lang="snobol">* GCD function
DEFINE('GCD(A,B)') :(GCD_END)
GCD GCD = A
EQ(B,0) :S(RETURN)
A = B
B = REMDR(GCD,B) :(GCD)
GCD_END
 
* Find first occurrence of element in array
<lang swift>struct SternBrocot: Sequence, IteratorProtocol {
DEFINE('IDX(ARR,ELM)') :(IDX_END)
IDX IDX = 1
ITEST EQ(ARR<IDX>,ELM) :S(RETURN)
IDX = IDX + 1 :(ITEST)
IDX_END
* Declare array
SEQ = ARRAY(1200,1)
 
* Fill array with Stern-Brocot sequence
IX = 1
FILL IX = IX + 1
SEQ<IX * 2 - 1> = SEQ<IX> + SEQ<IX - 1>
SEQ<IX * 2> = SEQ<IX> :S(FILL)
* Print first 15 elements
DONE IX = 1
S = "First 15 elements:"
P15 S = S " " SEQ<IX>
IX = IX + 1 LT(IX,15) :S(P15)
OUTPUT = S
* Print first occurrence of 1..10 and 100
N = 1
FIRSTN OUTPUT = "First " N " at " IDX(SEQ,N)
N = N + 1 LT(N,10) :S(FIRSTN)
OUTPUT = "First 100 at " IDX(SEQ,100)
* Test GCD between 1000 consecutive members
IX = 2
GCDTEST EQ(GCD(SEQ<IX - 1>,SEQ<IX>),1) :F(GCDFAIL)
IX = IX + 1 LT(IX,1000) :S(GCDTEST)
OUTPUT = "All GCDs are 1." :(END)
GCDFAIL OUTPUT = "GCD is not 1 at " IX "."
 
END</syntaxhighlight>
 
{{out}}
 
<pre>First 15 elements: 1 1 2 1 3 2 3 1 4 3 5 2 5 3 4
First 1 at 1
First 2 at 3
First 3 at 5
First 4 at 9
First 5 at 11
First 6 at 33
First 7 at 19
First 8 at 21
First 9 at 35
First 10 at 39
First 100 at 1179
All GCDs are 1.</pre>
 
=={{header|Swift}}==
<syntaxhighlight lang="swift">struct SternBrocot: Sequence, IteratorProtocol {
private var seq = [1, 1]
 
Line 4,231 ⟶ 6,370:
let gcdIsOne = zip(firstThousand, firstThousand.dropFirst()).allSatisfy({ gcd($0.0, $0.1) == 1 })
 
print("GCDs of all two consecutive members are \(gcdIsOne ? "" : "not")one")</langsyntaxhighlight>
 
{{out}}
Line 4,249 ⟶ 6,388:
 
=={{header|Tcl}}==
<langsyntaxhighlight lang="tcl">
#!/usr/bin/env tclsh
#
Line 4,354 ⟶ 6,493:
 
main
</syntaxhighlight>
</lang>
{{Out}}
<pre>
Line 4,377 ⟶ 6,516:
 
=={{header|VBScript}}==
<langsyntaxhighlight VBScriptlang="vbscript">sb = Array(1,1)
i = 1 'considered
j = 2 'precedent
Line 4,416 ⟶ 6,555:
End If
Next
End Function</langsyntaxhighlight>
{{Out}}
<pre>First 15: 1, 1, 2, 1, 3, 2, 3, 1, 4, 3, 5, 2, 5, 3, 4
Line 4,433 ⟶ 6,572:
=={{header|Visual Basic .NET}}==
{{trans|C#}}
<langsyntaxhighlight lang="vbnet">Imports System
Imports System.Collections.Generic
Imports System.Linq
Line 4,461 ⟶ 6,600:
" series up to the {0}th item is {1}always one.", max, If(good, "", "not "))
End Sub
End Module</langsyntaxhighlight>
{{out}}
<pre>The first 15 items In the Stern-Brocot sequence: 1, 1, 2, 1, 3, 2, 3, 1, 4, 3, 5, 2, 5, 3, 4
Line 4,479 ⟶ 6,618:
 
The greatest common divisor of all the two consecutive items of the series up to the 1000th item is always one.
</pre>
 
=={{header|Wren}}==
{{trans|Kotlin}}
{{libheader|Wren-math}}
{{libheader|Wren-fmt}}
<syntaxhighlight lang="wren">import "./math" for Int
import "./fmt" for Fmt
 
var sbs = [1, 1]
 
var sternBrocot = Fn.new { |n, fromStart|
if (n < 4 || (n % 2 != 0)) Fiber.abort("n must be >= 4 and even.")
var consider = fromStart ? 1 : (n/2).floor - 1
while (true) {
var sum = sbs[consider] + sbs[consider - 1]
sbs.add(sum)
sbs.add(sbs[consider])
if (sbs.count == n) return
consider = consider + 1
}
}
 
var n = 16 // needs to be even to ensure 'considered' number is added
System.print("First 15 members of the Stern-Brocot sequence:")
sternBrocot.call(n, true)
System.print(sbs.take(15).toList)
 
var firstFind = List.filled(11, 0)
firstFind[0] = -1 // needs to be non-zero for subsequent test
var i = 0
for (v in sbs) {
if (v <= 10 && firstFind[v] == 0) firstFind[v] = i + 1
i = i + 1
}
while (true) {
n = n + 2
sternBrocot.call(n, false)
var vv = sbs[-2..-1]
var m = n - 1
var outer = false
for (v in vv) {
if (v <= 10 && firstFind[v] == 0) firstFind[v] = m
if (firstFind.all { |e| e != 0 }) {
outer = true
break
}
m = m + 1
}
if (outer) break
}
System.print("\nThe numbers 1 to 10 first appear at the following indices:")
for (i in 1..10) Fmt.print("$2d -> $d", i, firstFind[i])
 
System.write("\n100 first appears at index ")
while (true) {
n = n + 2
sternBrocot.call(n, false)
var vv = sbs[-2..-1]
if (vv[0] == 100) {
System.print("%(n - 1).")
break
}
if (vv[1] == 100) {
System.print("%(n).")
break
}
}
 
System.write("\nThe GCDs of each pair of the series up to the 1,000th member are ")
var p = 0
while (p < 1000) {
if (Int.gcd(sbs[p], sbs[p + 1]) != 1) {
System.print("not all one.")
return
}
p = p + 2
}
System.print("all one.")</syntaxhighlight>
 
{{out}}
<pre>
First 15 members of the Stern-Brocot sequence:
[1, 1, 2, 1, 3, 2, 3, 1, 4, 3, 5, 2, 5, 3, 4]
 
The numbers 1 to 10 first appear at the following indices:
1 -> 1
2 -> 3
3 -> 5
4 -> 9
5 -> 11
6 -> 33
7 -> 19
8 -> 21
9 -> 35
10 -> 39
 
100 first appears at index 1179.
 
The GCDs of each pair of the series up to the 1,000th member are all one.
</pre>
 
=={{header|zkl}}==
<langsyntaxhighlight lang="zkl">fcn SB // Stern-Brocot sequence factory --> Walker
{ Walker(fcn(sb,n){ a,b:=sb; sb.append(a+b,b); sb.del(0); a }.fp(L(1,1))) }
 
Line 4,492 ⟶ 6,731:
[1..].zip(SB()).filter1(fcn(sb){ 100==sb[1] }).println();
 
sb:=SB(); do(500){ if(sb.next().gcd(sb.next())!=1) println("Oops") }</langsyntaxhighlight>
{{out}}
<pre>
9,476

edits