Stern-Brocot sequence: Difference between revisions
Content deleted Content added
Stern-Brocot sequence in various BASIC dialents |
|||
(15 intermediate revisions by 10 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
* 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>
Line 46:
{{trans|Python}}
<
V sb = [1, 1]
V i = 0
Line 65:
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’)</
{{out}}
Line 87:
=={{header|360 Assembly}}==
{{trans|Fortran}}
<
STERNBR CSECT
USING STERNBR,R13 base register
Line 158:
SB DC (NN)H'1' sb(nn)
REGEQU
END STERNBR</
{{out}}
<pre>
Line 176:
</pre>
The nice part is the coding of the sequense:
<
while(k<nn);
k++; sb[k]=sb[k-i]+sb[k-j];
k++; sb[k]=sb[k-j];
i++; j++;
} </
Only five registers are used. No Horner's rule to access sequence items.
<
LA R2,SB+2 i=1; @sb(k-i)
LA R3,SB+0 j=2; @sb(k-j)
Line 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 </
=={{header|8080 Assembly}}==
<syntaxhighlight 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 335 ⟶ 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</
{{out}}
Line 345 ⟶ 344:
=={{header|8086 Assembly}}==
<syntaxhighlight lang="asm">puts: equ 9
cpu 8086
bits 16
Line 446 ⟶ 444:
numbuf: db ' $'
nl: db 13,10,'$'
seq: db 1,1</
{{out}}
Line 454 ⟶ 452:
1179
GCD of all pairs of consecutive members is 1.</pre>
=={{header|Action!}}==
<
INT i
Line 533 ⟶ 529:
PrintLoc(seq,count,loc,11)
PrintGcd(seq,1000)
RETURN</
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Stern-Brocot_sequence.png Screenshot from Atari 8-bit computer]
Line 556 ⟶ 552:
=={{header|Ada}}==
<syntaxhighlight lang="ada">with Ada.Text_IO, Ada.Containers.Vectors;
procedure Sequence is
Line 650 ⟶ 645:
when Constraint_Error => Put_Line("Some GCD > 1; this is wrong!!!") ;
end;
end Sequence;</
{{out}}
Line 661 ⟶ 656:
=={{header|ALGOL 68}}==
<
# subsequent members are the previous two members summed followed by #
# the previous #
Line 734 ⟶ 729:
OD;
print( ( "Element pairs up to 1000 are ", IF all coprime THEN "" ELSE "NOT " FI, "coprime", newline ) )
END</
{{out}}
<pre>
Line 748 ⟶ 743:
=={{header|ALGOL-M}}==
<
integer array S[1:1200];
integer i,ok;
Line 796 ⟶ 791:
end;
if ok = 1 then write("The GCD of each pair of consecutive members is 1.");
end</
{{out}}
<pre>First 15 numbers:
Line 817 ⟶ 812:
The GCD of each pair of consecutive members is 1.</pre>
=={{header|
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 ⋄ ⍺⍺≤⍴⍵:⍺⍺↑⍵
Line 829 ⟶ 881:
⎕←'Location of 100:',seq⍳100
⎕←'All GCDs 1:','no' 'yes'[1+1∧.=2∨/1000↑seq]
}</
{{out}}
Line 839 ⟶ 891:
=={{header|AppleScript}}==
<
use framework "Foundation"
use scripting additions
Line 1,379 ⟶ 1,431:
return lst
end tell
end zipWith</
{{Out}}
<pre>[1,1,2,1,3,2,3,1,4,3,5,2,5,3,4]
Line 1,385 ⟶ 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}}==
<
Loop, 10
FoundList .= "First " A_Index " found at " Found[A_Index] "`n"
Line 1,463 ⟶ 1,586:
b := Mod(a | 0x0, a := b)
return a
}</
{{out}}
<pre>First 15: 1, 1, 2, 1, 3, 2, 3, 1, 4, 3, 5, 2, 5, 3, 4
Line 1,480 ⟶ 1,603:
=={{header|BASIC}}==
<syntaxhighlight 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,502 ⟶ 1,624:
190 NEXT I
200 PRINT "All GCDs are 1."
210 END</
{{out}}
Line 1,523 ⟶ 1,645:
==={{header|BASIC256}}===
{{trans|FreeBASIC}}
<
max = 2000
global stern
Line 1,585 ⟶ 1,707:
else
print "The GCD for index "; i; " and "; i+1; " = "; d
end if</
{{out}}
<pre>Igual que la entrada de FreeBASIC.</pre>
Line 1,592 ⟶ 1,714:
{{trans|FreeBASIC}}
{{works with|QBasic|1.1}}
<
DIM SHARED stern(max + 2)
Line 1,652 ⟶ 1,774:
ELSE
PRINT "The GCD for index "; i; " and "; i + 1; " = "; d
END IF</
{{out}}
<pre>Igual que la entrada de FreeBASIC.</pre>
Line 1,658 ⟶ 1,780:
==={{header|Yabasic}}===
{{trans|FreeBASIC}}
<
dim stern(limite+2)
Line 1,713 ⟶ 1,835:
else
print "The GCD for index ", i, " and ", i+1, " = ", d
end if</
{{out}}
<pre>Igual que la entrada de FreeBASIC.</pre>
=={{header|BCPL}}==
<
manifest $( AMOUNT = 1200 $)
Line 1,761 ⟶ 1,883:
$) then
writes("*NThe GCD of each pair of consecutive members is 1.*N")
$)</
{{out}}
<pre>First 15 numbers: 1 1 2 1 3 2 3 1 4 3 5 2 5 3 4
Line 1,779 ⟶ 1,901:
The GCD of each pair of consecutive members is 1.</pre>
=={{header|C}}==
Recursive function.
<
typedef unsigned int uint;
Line 1,818 ⟶ 1,941:
return 0;
}</
{{out}}
<pre>
Line 1,836 ⟶ 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.
<
{
uint a = 1, b = 0;
Line 1,845 ⟶ 1,968:
}
return b;
}</
=={{header|C sharp|C#}}==
<
using System.Collections.Generic;
using System.Linq;
Line 1,873 ⟶ 1,996:
" series up to the {0}th item is {1}always one.", max, good ? "" : "not ");
}
}</
{{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,894 ⟶ 2,017:
=={{header|C++}}==
<
#include <iostream>
#include <iomanip>
Line 1,945 ⟶ 2,068:
return 0;
}
</syntaxhighlight>
{{out}}
<pre>
Line 1,988 ⟶ 2,111:
=={{header|Clojure}}==
<
(defn sb-step [v]
(let [i (quot (count v) 2)]
Line 2,021 ⟶ 2,144:
true)
(report-sb)</
{{Output}}
Line 2,041 ⟶ 2,164:
===Clojure: Using Lazy Sequences===
<
(defn gcd
"(gcd a b) computes the greatest common divisor of a and b."
Line 2,073 ⟶ 2,196:
(println (every? (fn [[ith ith-plus-1]] (= (gcd ith ith-plus-1) 1))
one-thousand-pairs))
</syntaxhighlight>
{{Output}}
Line 2,093 ⟶ 2,216:
=={{header|CLU}}==
<
s: array[int] := array[int]$fill(1, n, 1)
for i: int in int$from_to(2, n/2) do
Line 2,143 ⟶ 2,266:
stream$putl(po, "The GCD of the pair at " || int$unparse(i) || " is not 1.")
end
end start_up</
{{out}}
<pre>First 15 numbers: 1 1 2 1 3 2 3 1 4 3 5 2 5 3 4
Line 2,160 ⟶ 2,283:
=={{header|Common Lisp}}==
<
(declare ((or null (vector integer)) numbers))
(cond ((null numbers)
Line 2,215 ⟶ 2,338:
(first-1-to-10)
(first-100)
(check-gcd))</
{{out}}
<pre>First 15: 1 1 2 1 3 2 3 1 4 3 5 2 5 3 4
Line 2,232 ⟶ 2,355:
=={{header|Cowgol}}==
<
# Redefining these is enough to change the type and length everywhere,
Line 2,308 ⟶ 2,431:
end loop;
print("All GCDs are 1.\n");</
{{out}}
Line 2,318 ⟶ 2,441:
=={{header|D}}==
{{trans|Python}}
<
/// Generates members of the stern-brocot series, in order,
Line 2,346 ⟶ 2,469:
assert(zip(s, s.dropOne).all!(ss => ss[].gcd == 1),
"A fraction from adjacent terms is reducible.");
}</
{{out}}
<pre>The first 15 values:
Line 2,364 ⟶ 2,487:
This uses a queue from the Queue/usage Task:
<
struct SternBrocot {
Line 2,381 ⟶ 2,504:
void main() {
SternBrocot().drop(50_000_000).front.writeln;
}</
{{out}}
<pre>7004</pre>
Line 2,387 ⟶ 2,510:
<b>Direct Version:</b>
{{trans|C}}
<
import std.stdio, std.numeric, std.range, std.algorithm, std.bigint, std.conv;
Line 2,414 ⟶ 2,537:
sternBrocot(10.BigInt ^^ 20_000).text.length.writeln;
}</
{{out}}
<pre>The first 15 values:
Line 2,431 ⟶ 2,554:
1-based index of the first occurrence of 100 in the series: 1179
7984</pre>
=={{header|EasyLang}}==
{{trans|Lua}}
<syntaxhighlight lang=text>
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 ===
<
;; stern (2n ) = stern (n)
;; stern(2n+1) = stern(n) + stern(n+1)
Line 2,444 ⟶ 2,644:
(else (let ((m (/ (1- n) 2))) (+ (stern m) (stern (1+ m)))))))
(remember 'stern)
</syntaxhighlight>
{{out}}
<
; generate the sequence and check GCD
(for ((n 10000))
Line 2,467 ⟶ 2,667:
(stern 900000) → 446
(stern 900001) → 2479
</syntaxhighlight>
=== 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).
<
;; grouping
(for ((i (in-range 2 40 2))) (write (/ (stern i)(stern (1+ i)))))
Line 2,486 ⟶ 2,686:
→ 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>
=={{header|Elixir}}==
<
def sequence do
Stream.unfold({0,{1,1}}, fn {i,acc} ->
Line 2,516 ⟶ 2,716:
end
SternBrocot.task</
{{out}}
Line 2,538 ⟶ 2,738:
=={{header|F_Sharp|F#}}==
===The function===
<
// 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>
===The Task===
Uses [[Greatest_common_divisor#F.23]]
<
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>
{{out}}
<pre>
Line 2,560 ⟶ 2,760:
=={{header|Factor}}==
Using the alternative function given in the C example for computing the Stern-Brocot sequence.
<
math.ranges prettyprint sequences ;
IN: rosetta-code.stern-brocot
Line 2,590 ⟶ 2,790:
: main ( -- ) first15 first-appearances gcd-test ;
MAIN: main</
{{out}}
<pre>
Line 2,609 ⟶ 2,809:
=={{header|Forth}}==
<syntaxhighlight lang="forth">: stern ( n -- x : return N'th item of Stern-Brocot sequence)
dup 2 >= if
2 /mod swap if
Line 2,662 ⟶ 2,861:
task
bye</
{{out}}
Line 2,684 ⟶ 2,883:
{{trans|VBScript}}
===Fortran IV===
<
DIMENSION ISB(2400)
NN=2400
Line 2,714 ⟶ 2,913:
103 FORMAT(1X,'FIRST',I4,' AT ',I4)
5 CONTINUE
END </
{{out}}
<pre>
Line 2,733 ⟶ 2,932:
</pre>
===Fortran 90===
<
parameter (nn=2400)
dimension isb(nn)
Line 2,754 ⟶ 2,953:
write(*,"(1x,'First',i4,' at ',i4)") jj,i
end do
end </
{{out}}
<pre>
Line 2,773 ⟶ 2,972:
=={{header|FreeBASIC}}==
<
' compile with: fbc -s console
Line 2,854 ⟶ 3,053:
Print : Print "hit any key to end program"
Sleep
End</
{{out}}
<pre>The first 15 are: 1 1 2 1 3 2 3 1 4 3 5 2 5 3 4
Line 2,874 ⟶ 3,073:
=={{header|Go}}==
<
import (
Line 2,921 ⟶ 3,120:
}
return x
}</
<
//
// Generator() satisfies RC Task 1. For remaining tasks, Generator could be
Line 2,995 ⟶ 3,194:
}
}
}</
{{out}}
<pre>
Line 3,037 ⟶ 3,236:
=={{header|Haskell}}==
<
sb :: [Int]
Line 3,053 ⟶ 3,252:
print $
all (\(a, b) -> 1 == gcd a b) $
take 1000 $ zip sb (tail sb)</
{{out}}
<pre>[1,1,2,1,3,2,3,1,4,3,5,2,5,3,4]
Line 3,061 ⟶ 3,260:
Or, expressed in terms of iterate:
<
import Data.List (nubBy, sortOn)
import Data.Ord (comparing)
Line 3,088 ⟶ 3,287:
print $
(all ((1 ==) . uncurry gcd) . (zip <*> tail)) $
take 1000 sternBrocot</
{{Out}}
<pre>[1,1,2,1,3,2,3,1,4,3,5,2,5,3,4]
Line 3,096 ⟶ 3,295:
=={{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:
<
ind=. 0
seq=. 1 1
Line 3,106 ⟶ 3,304:
seq=. seq, +/\. seq {~ _1 0 +ind
end.
)</
(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 3,112 ⟶ 3,310:
First fifteen members of the sequence:
<
1 1 2 1 3 2 3 1 4 3 5 2 5 3 4</
One based indices of where numbers 1-10 first appear in the sequence:
<
1 3 5 9 11 33 19 21 35 39</
One based index of where the number 100 first appears:
<
1179</
List of distinct greatest common divisors of adjacent number pairs from a sternbrocot sequence which includes the first 1000 elements:
<
1</
=={{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.
<
import java.util.LinkedList;
Line 3,166 ⟶ 3,364:
System.out.println("All GCDs are" + (failure ? " not" : "") + " 1");
}
}</
{{out}}
<pre>The first 15 elements are: [1, 1, 2, 1, 3, 2, 3, 1, 4, 3, 5, 2, 5, 3, 4]
Line 3,184 ⟶ 3,382:
=== Stern-Brocot Tree ===
{{works with|Java|8}}
<
import javax.swing.*;
Line 3,246 ⟶ 3,444:
});
}
}</
[[File:stern_brocot_tree_java.gif]]
=={{header|JavaScript}}==
<
'use strict';
Line 3,574 ⟶ 3,772:
// MAIN ---
return main();
})();</
{{Out}}
<pre>[1,1,2,1,3,2,3,1,4,3,5,2,5,3,4]
Line 3,586 ⟶ 3,784:
'''Foundations:'''
<
def _until:
if cond then . else (update | _until) end;
Line 3,597 ⟶ 3,795:
else [.[1], .[0] % .[1]] | rgcd
end;
[a,b] | rgcd ;</
'''The A002487 integer sequence:'''
Line 3,604 ⟶ 3,802:
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.
<
# generates an array with at least n elements of
# the A002487 sequence;
Line 3,621 ⟶ 3,819:
| if (.[$l-2] == -n) then .
else .[$l + 1] = .[$n] + .[$n+1]
end ) ;</
'''The tasks:'''
<
def stern_brocot(n): A002487(n+1) | .[1:n+1][];
Line 3,654 ⟶ 3,852:
"",
gcd_task
</syntaxhighlight>
{{out}}
<
First 15 integers of the Stern-Brocot sequence
as defined in the task description are:
Line 3,688 ⟶ 3,886:
index of 100 is 1179
GCDs are all 1</
=={{header|Julia}}==
{{trans|Python}}
<
function sternbrocot(f::Function=(x) -> length(x) ≥ 20)::Vector{Int}
Line 3,717 ⟶ 3,915:
else
println("Rejected.")
end</
{{out}}
Line 3,740 ⟶ 3,938:
=={{header|Kotlin}}==
<
val sbs = mutableListOf(1, 1)
Line 3,803 ⟶ 4,001:
}
println("all one")
}</
{{out}}
Line 3,828 ⟶ 4,026:
=={{header|Lua}}==
<
function sternBrocot (n)
local sbList, pos, c = {1, 1}, 2
Line 3,876 ⟶ 4,074:
for i = 1, 10 do print("\t" .. i, findFirst(sb, i)) end
print("\nTask 4: " .. findFirst(sb, 100))
print("\nTask 5: " .. task5(sb))</
{{out}}
<pre>Task 2: 1 1 2 1 3 2 3 1 4 3 5 2 5 3 4
Line 3,896 ⟶ 4,094:
Task 5: PASS</pre>
=={{header|
<syntaxhighlight lang="macro11"> .TITLE STNBRC
.MCALL .TTYOUT,.EXIT
AMOUNT = ^D1200
STNBRC::JSR PC,GENSEQ
; PRINT FIRST 15
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*$
Line 3,928 ⟶ 4,273:
SCAN WHENEVER N .E. STERN(K), FUNCTION RETURN K
END OF FUNCTION
END OF PROGRAM</
{{out}}
Line 3,961 ⟶ 4,306:
=={{header|Mathematica}} / {{header|Wolfram Language}}==
<
Do[
sb = sb~Join~{Total@sb[[i - 1 ;; i]], sb[[i]]}
Line 3,970 ⟶ 4,315:
Flatten[FirstPosition[sb, #] & /@ Range[10]]
First@FirstPosition[sb, 100]
AllTrue[Partition[Take[sb, 1000], 2, 1], Apply[GCD] /* EqualTo[1]]</
{{out}}
<pre>{1, 1, 2, 1, 3, 2, 3, 1, 4, 3, 5, 2, 5, 3, 4}
Line 3,976 ⟶ 4,321:
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}}==
<
FROM InOut IMPORT WriteString, WriteCard, WriteLn;
Line 4,052 ⟶ 4,439:
WriteString("The GCD of every pair of adjacent elements is 1.");
WriteLn;
END SternBrocot.</
{{out}}
<pre>First 15 numbers: 1 1 2 1 3 2 3 1 4 3 5 2 5 3 4
Line 4,072 ⟶ 4,459:
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.
<
iterator sternBrocot(): (int, int) =
Line 4,128 ⟶ 4,515:
echo "Found two successive terms at index: ", index
else:
echo "All consecutive terms up to the 1000th member have a GCD equal to one."</
{{out}}
Line 4,147 ⟶ 4,534:
All consecutive terms up to the 1000th member have a GCD equal to one.</pre>
=={{header|
<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 4,155 ⟶ 4,585:
n 2 mod ifFalse: [ dup removeLast drop ] dup freeze ;
stern(10000) Constant new: Sterns</
{{out}}
Line 4,186 ⟶ 4,616:
{{Works with|PARI/GP|2.7.4 and above}}
<
\\ Stern-Brocot sequence
\\ 5/27/16 aev
Line 4,214 ⟶ 4,644:
if(j==1, print("Yes"), print("No"));
}
</
{{Output}}
Line 4,226 ⟶ 4,656:
=={{header|Pascal}}==
{{works with|Free Pascal}}
<
{$IFDEF FPC}
{$MODE DELPHI}
Line 4,312 ⟶ 4,742:
writeln('GCD-test is O.K.');
setlength(seq,0);
end.</
1 @ 1,2 @ 3,3 @ 5,4 @ 9,5 @ 11,6 @ 33,7 @ 38,8 @ 42,9 @ 47,10 @ 57
100 @ 1179
Line 4,318 ⟶ 4,748:
=={{header|Perl}}==
<
use warnings;
Line 4,353 ⟶ 4,783:
($a, $b) = ($b, $generator->());
}
}</
{{out}}
<pre>1 1 2 1 3 2 3 1 4 3 5 2 5 3 4
Line 4,369 ⟶ 4,799:
A slightly different method:{{libheader|ntheory}}
<
sub stern_diatomic {
Line 4,387 ⟶ 4,817:
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";</
{{out}}
<pre>First fifteen: [1 1 2 1 3 2 3 1 4 3 5 2 5 3 4]
Line 4,395 ⟶ 4,825:
=={{header|Phix}}==
<!--<
<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>
<span style="color: #004080;">integer</span> <span style="color: #000000;">c</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">2</span>
Line 4,437 ⟶ 4,867:
<span style="color: #008080;">end</span> <span style="color: #008080;">for</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;">"max gcd:%d\n"</span><span style="color: #0000FF;">,{</span><span style="color: #000000;">maxgcd</span><span style="color: #0000FF;">})</span>
<!--</
{{Out}}
<pre>
Line 4,449 ⟶ 4,879:
{{trans|C}}
Using the <tt>gcd</tt> function defined at ''[[Greatest_common_divisor#PicoLisp]]'':
<
(let (A 1 B 0)
(while (gt0 N)
Line 4,465 ⟶ 4,895:
(for (L Lst (cdr L) (cddr L))
(test 1 (gcd (car L) (cadr L))) )
(prinl "All consecutive pairs are relative prime!") )</
{{out}}
<pre>
Line 4,484 ⟶ 4,914:
=={{header|PL/I}}==
<
%replace MAX by 1200;
declare S(1:MAX) fixed;
Line 4,531 ⟶ 4,961:
end;
put skip list('All GCDs of adjacent pairs are 1.');
end sternBrocot;</
{{out}}
<pre>First 15 elements: 1 1 2 1 3 2 3 1 4 3 5 2 5 3 4
Line 4,548 ⟶ 4,978:
=={{header|PL/M}}==
<
/* FIND LOCATION OF FIRST ELEMENT IN ARRAY */
FIND$FIRST: PROCEDURE (ARR, EL) ADDRESS;
Line 4,635 ⟶ 5,065:
CALL PRINT(.'ALL GCDS ARE 1$');
CALL BDOS(0,0);
EOF</
{{out}}
<pre>FIRST 15 ELEMENTS: 1 1 2 1 3 2 3 1 4 3 5 2 5 3 4
Line 4,652 ⟶ 5,082:
=={{header|PowerShell}}==
<syntaxhighlight lang="powershell">
# An iterative approach
function iter_sb($count = 2000)
Line 4,681 ⟶ 5,111:
'GCD = 1 for first 1000 members: {0}' -f $gcd
}
</syntaxhighlight>
{{out}}
Line 4,716 ⟶ 5,146:
=={{header|PureBasic}}==
<
Define.i i
Line 4,766 ⟶ 5,196:
EndIf
Input()</
{{out}}
<pre>Stern-Brocot_sequence
Line 4,787 ⟶ 5,217:
=={{header|Python}}==
===Python: procedural===
<
"""\
Generates members of the stern-brocot series, in order, returning them when the predicate becomes false
Line 4,822 ⟶ 5,252:
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'</
{{out}}
Line 4,845 ⟶ 5,275:
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'
<
>>> from collections import deque
>>> from fractions import gcd
Line 4,866 ⟶ 5,296:
>>> all(gcd(p, t) == 1 for p, t in islice(zip(prev, this), 1000))
True
>>> </
===Python: Composing pure (curried) functions===
Line 4,872 ⟶ 5,302:
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}}
<
import math
Line 5,049 ⟶ 5,479:
# MAIN ---
if __name__ == '__main__':
main()</
{{Out}}
<pre>[1, 1, 2, 1, 3, 2, 3, 1, 4, 3, 5, 2, 5, 3, 4]
Line 5,055 ⟶ 5,485:
[(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 5,062 ⟶ 5,529:
{{libheader|pracma}}
<
## Stern-Brocot sequence
## 12/19/16 aev
Line 5,085 ⟶ 5,552:
if(j==1) {cat(" *** All GCDs=1!\n")} else {cat(" *** All GCDs!=1??\n")}
}
</
{{Output}}
Line 5,103 ⟶ 5,570:
As with the previous solution, we have used a library for our gcd function. In this case, we have used gmp.
<
{
sternNums <- c(1, 1)
Line 5,123 ⟶ 5,590:
match(1:10, firstFiveThousandTerms)
match(100, firstFiveThousandTerms)
all(sapply(1:999, function(i) gmp::gcd(firstFiveThousandTerms[i], firstFiveThousandTerms[i + 1])) == 1)</
{{Output}}
<pre>> firstFiveThousandTerms <- genNStern(5000)
Line 5,134 ⟶ 5,601:
=={{header|Racket}}==
<syntaxhighlight lang="racket">#lang racket
;; OEIS Definition
;; A002487
Line 5,172 ⟶ 5,638:
(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"))</
{{out}}
Line 5,198 ⟶ 5,664:
(formerly Perl 6)
{{works with|rakudo|2017-03}}
<syntaxhighlight lang="raku"
put @Stern-Brocot[^15];
Line 5,206 ⟶ 5,672:
}
say so 1 == all map ^1000: { [gcd] @Stern-Brocot[$_, $_ + 1] }</
{{out}}
<pre>1 1 2 1 3 2 3 1 4 3 5 2 5 3 4
Line 5,222 ⟶ 5,688:
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}}==
<
parse arg N idx fix chk . /*get optional arguments from the C.L. */
if N=='' | N=="," then N= 15 /*Not specified? Then use the default.*/
Line 5,272 ⟶ 5,808:
end /*k*/
if f==0 then return subword($, 1, h)
return $</
{{out|output|text= when using the default inputs:}}
<pre>
Line 5,298 ⟶ 5,834:
=={{header|Ring}}==
<
# Project : Stern-Brocot sequence
Line 5,352 ⟶ 5,888:
end
return gcd
</syntaxhighlight>
Output:
<pre>
Line 5,369 ⟶ 5,905:
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}}
<
return enum_for :sb unless block_given?
a=[1,1]
Line 5,391 ⟶ 6,032:
else
puts "Whoops, not all GCD's are 1!"
end</
{{out}}
Line 5,411 ⟶ 6,052:
=={{header|Scala}}==
<
BigInt("1") #::
BigInt("1") #::
Line 5,429 ⟶ 6,070:
(sbSeq zip sbSeq.tail).take(1000).forall{ case (a,b) => a.gcd(b) == 1 } )
}
</syntaxhighlight>
{{out}}
Line 5,450 ⟶ 6,091:
</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}}
<
func stern_brocot {
var list = [1, 1]
Line 5,485 ⟶ 6,248:
} * 1000
say "All GCD's are 1"</
{{out}}
<pre>
Line 5,504 ⟶ 6,267:
=={{header|Snobol}}==
<syntaxhighlight lang="snobol">* GCD function
DEFINE('GCD(A,B)') :(GCD_END)
GCD GCD = A
Line 5,549 ⟶ 6,311:
GCDFAIL OUTPUT = "GCD is not 1 at " IX "."
END</
{{out}}
Line 5,566 ⟶ 6,328:
First 100 at 1179
All GCDs are 1.</pre>
=={{header|Swift}}==
<syntaxhighlight lang="swift">struct SternBrocot: Sequence, IteratorProtocol {
private var seq = [1, 1]
Line 5,609 ⟶ 6,369:
let gcdIsOne = zip(firstThousand, firstThousand.dropFirst()).allSatisfy({ gcd($0.0, $0.1) == 1 })
print("GCDs of all two consecutive members are \(gcdIsOne ? "" : "not")one")</
{{out}}
Line 5,627 ⟶ 6,387:
=={{header|Tcl}}==
<
#!/usr/bin/env tclsh
#
Line 5,732 ⟶ 6,492:
main
</syntaxhighlight>
{{Out}}
<pre>
Line 5,755 ⟶ 6,515:
=={{header|VBScript}}==
<
i = 1 'considered
j = 2 'precedent
Line 5,794 ⟶ 6,554:
End If
Next
End Function</
{{Out}}
<pre>First 15: 1, 1, 2, 1, 3, 2, 3, 1, 4, 3, 5, 2, 5, 3, 4
Line 5,811 ⟶ 6,571:
=={{header|Visual Basic .NET}}==
{{trans|C#}}
<
Imports System.Collections.Generic
Imports System.Linq
Line 5,839 ⟶ 6,599:
" series up to the {0}th item is {1}always one.", max, If(good, "", "not "))
End Sub
End Module</
{{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 5,863 ⟶ 6,623:
{{libheader|Wren-math}}
{{libheader|Wren-fmt}}
<
import "./fmt" for Fmt
var sbs = [1, 1]
Line 5,935 ⟶ 6,695:
p = p + 2
}
System.print("all one.")</
{{out}}
Line 5,960 ⟶ 6,720:
=={{header|zkl}}==
<
{ Walker(fcn(sb,n){ a,b:=sb; sb.append(a+b,b); sb.del(0); a }.fp(L(1,1))) }
Line 5,970 ⟶ 6,730:
[1..].zip(SB()).filter1(fcn(sb){ 100==sb[1] }).println();
sb:=SB(); do(500){ if(sb.next().gcd(sb.next())!=1) println("Oops") }</
{{out}}
<pre>
|