Stern-Brocot sequence: Difference between revisions

m
syntax highlighting fixup automation
(Added Quackery.)
m (syntax highlighting fixup automation)
Line 46:
{{trans|Python}}
 
<langsyntaxhighlight lang="11l">F stern_brocot(predicate = series -> series.len < 20)
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’)</langsyntaxhighlight>
 
{{out}}
Line 87:
=={{header|360 Assembly}}==
{{trans|Fortran}}
<langsyntaxhighlight lang="360asm">* Stern-Brocot sequence - 12/03/2019
STERNBR CSECT
USING STERNBR,R13 base register
Line 158:
SB DC (NN)H'1' sb(nn)
REGEQU
END STERNBR</langsyntaxhighlight>
{{out}}
<pre>
Line 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 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}}==
 
<langsyntaxhighlight 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:
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 346:
=={{header|8086 Assembly}}==
 
<langsyntaxhighlight lang="asm">puts: equ 9
cpu 8086
bits 16
Line 446:
numbuf: db ' $'
nl: db 13,10,'$'
seq: db 1,1</langsyntaxhighlight>
 
{{out}}
Line 458:
 
=={{header|Action!}}==
<langsyntaxhighlight Actionlang="action!">PROC Generate(BYTE ARRAY seq INT POINTER count INT minCount,maxVal)
INT i
 
Line 533:
PrintLoc(seq,count,loc,11)
PrintGcd(seq,1000)
RETURN</langsyntaxhighlight>
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Stern-Brocot_sequence.png Screenshot from Atari 8-bit computer]
Line 557:
=={{header|Ada}}==
 
<langsyntaxhighlight Adalang="ada">with Ada.Text_IO, Ada.Containers.Vectors;
 
procedure Sequence is
Line 650:
when Constraint_Error => Put_Line("Some GCD > 1; this is wrong!!!") ;
end;
end Sequence;</langsyntaxhighlight>
 
{{out}}
Line 661:
 
=={{header|ALGOL 68}}==
<langsyntaxhighlight 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 #
Line 734:
OD;
print( ( "Element pairs up to 1000 are ", IF all coprime THEN "" ELSE "NOT " FI, "coprime", newline ) )
END</langsyntaxhighlight>
{{out}}
<pre>
Line 748:
 
=={{header|ALGOL-M}}==
<langsyntaxhighlight lang="algolm">begin
integer array S[1:1200];
integer i,ok;
Line 796:
end;
if ok = 1 then write("The GCD of each pair of consecutive members is 1.");
end</langsyntaxhighlight>
{{out}}
<pre>First 15 numbers:
Line 819:
=={{header|Amazing Hopper}}==
Version: hopper-FLOW!:
<syntaxhighlight lang="amazing hopper">
<lang Amazing Hopper>
#include <flow.h>
#include <flow-flow.h>
Line 857:
NEXT
RET
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 877:
=={{header|APL}}==
 
<langsyntaxhighlight APLlang="apl">task←{
stern←{⍵{
⍺←0 ⋄ ⍺⍺≤⍴⍵:⍺⍺↑⍵
Line 887:
⎕←'Location of 100:',seq⍳100
⎕←'All GCDs 1:','no' 'yes'[1+1∧.=2∨/1000↑seq]
}</langsyntaxhighlight>
 
{{out}}
Line 897:
 
=={{header|AppleScript}}==
<langsyntaxhighlight lang="applescript">use AppleScript version "2.4"
use framework "Foundation"
use scripting additions
Line 1,437:
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,445:
 
=={{header|AutoHotkey}}==
<langsyntaxhighlight AutoHotkeylang="autohotkey">Found := FindOneToX(100), FoundList := ""
Loop, 10
FoundList .= "First " A_Index " found at " Found[A_Index] "`n"
Line 1,521:
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,539:
=={{header|BASIC}}==
 
<langsyntaxhighlight 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,560:
190 NEXT I
200 PRINT "All GCDs are 1."
210 END</langsyntaxhighlight>
 
{{out}}
Line 1,581:
==={{header|BASIC256}}===
{{trans|FreeBASIC}}
<langsyntaxhighlight lang="basic256">arraybase 1
max = 2000
global stern
Line 1,643:
else
print "The GCD for index "; i; " and "; i+1; " = "; d
end if</langsyntaxhighlight>
{{out}}
<pre>Igual que la entrada de FreeBASIC.</pre>
Line 1,650:
{{trans|FreeBASIC}}
{{works with|QBasic|1.1}}
<langsyntaxhighlight QBasiclang="qbasic">CONST max = 2000
DIM SHARED stern(max + 2)
 
Line 1,710:
ELSE
PRINT "The GCD for index "; i; " and "; i + 1; " = "; d
END IF</langsyntaxhighlight>
{{out}}
<pre>Igual que la entrada de FreeBASIC.</pre>
Line 1,716:
==={{header|Yabasic}}===
{{trans|FreeBASIC}}
<langsyntaxhighlight lang="yabasic">limite = 2000
dim stern(limite+2)
 
Line 1,771:
else
print "The GCD for index ", i, " and ", i+1, " = ", d
end if</langsyntaxhighlight>
{{out}}
<pre>Igual que la entrada de FreeBASIC.</pre>
 
=={{header|BCPL}}==
<langsyntaxhighlight lang="bcpl">get "libhdr"
 
manifest $( AMOUNT = 1200 $)
Line 1,819:
$) then
writes("*NThe GCD of each pair of consecutive members is 1.*N")
$)</langsyntaxhighlight>
{{out}}
<pre>First 15 numbers: 1 1 2 1 3 2 3 1 4 3 5 2 5 3 4
Line 1,839:
=={{header|C}}==
Recursive function.
<langsyntaxhighlight lang="c">#include <stdio.h>
 
typedef unsigned int uint;
Line 1,876:
 
return 0;
}</langsyntaxhighlight>
{{out}}
<pre>
Line 1,894:
</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,903:
}
return b;
}</langsyntaxhighlight>
 
=={{header|C sharp|C#}}==
<langsyntaxhighlight lang="csharp">using System;
using System.Collections.Generic;
using System.Linq;
Line 1,931:
" 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,952:
 
=={{header|C++}}==
<langsyntaxhighlight lang="cpp">
#include <iostream>
#include <iomanip>
Line 2,003:
return 0;
}
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 2,046:
 
=={{header|Clojure}}==
<langsyntaxhighlight lang="clojure">;; each step adds two items
(defn sb-step [v]
(let [i (quot (count v) 2)]
Line 2,079:
true)
 
(report-sb)</langsyntaxhighlight>
 
{{Output}}
Line 2,099:
 
===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 2,131:
(println (every? (fn [[ith ith-plus-1]] (= (gcd ith ith-plus-1) 1))
one-thousand-pairs))
</syntaxhighlight>
</lang>
{{Output}}
 
Line 2,151:
 
=={{header|CLU}}==
<langsyntaxhighlight 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
Line 2,201:
stream$putl(po, "The GCD of the pair at " || int$unparse(i) || " is not 1.")
end
end start_up</langsyntaxhighlight>
{{out}}
<pre>First 15 numbers: 1 1 2 1 3 2 3 1 4 3 5 2 5 3 4
Line 2,218:
 
=={{header|Common Lisp}}==
<langsyntaxhighlight lang="lisp">(defun stern-brocot (numbers)
(declare ((or null (vector integer)) numbers))
(cond ((null numbers)
Line 2,273:
(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 2,290:
 
=={{header|Cowgol}}==
<langsyntaxhighlight lang="cowgol">include "cowgol.coh";
 
# Redefining these is enough to change the type and length everywhere,
Line 2,366:
end loop;
 
print("All GCDs are 1.\n");</langsyntaxhighlight>
 
{{out}}
Line 2,376:
=={{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 2,404:
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 2,422:
 
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 2,439:
void main() {
SternBrocot().drop(50_000_000).front.writeln;
}</langsyntaxhighlight>
{{out}}
<pre>7004</pre>
Line 2,445:
<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 2,472:
 
sternBrocot(10.BigInt ^^ 20_000).text.length.writeln;
}</langsyntaxhighlight>
{{out}}
<pre>The first 15 values:
Line 2,492:
=={{header|EchoLisp}}==
=== Function ===
<langsyntaxhighlight lang="lisp">
;; stern (2n ) = stern (n)
;; stern(2n+1) = stern(n) + stern(n+1)
Line 2,502:
(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 2,525:
(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 2,544:
 
→ 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 2,574:
end
 
SternBrocot.task</langsyntaxhighlight>
 
{{out}}
Line 2,596:
=={{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 2,618:
=={{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 2,648:
: main ( -- ) first15 first-appearances gcd-test ;
 
MAIN: main</langsyntaxhighlight>
{{out}}
<pre>
Line 2,668:
=={{header|Forth}}==
 
<langsyntaxhighlight lang="forth">: stern ( n -- x : return N'th item of Stern-Brocot sequence)
dup 2 >= if
2 /mod swap if
Line 2,720:
 
task
bye</langsyntaxhighlight>
 
{{out}}
Line 2,742:
{{trans|VBScript}}
===Fortran IV===
<langsyntaxhighlight lang="fortran">* STERN-BROCOT SEQUENCE - FORTRAN IV
DIMENSION ISB(2400)
NN=2400
Line 2,772:
103 FORMAT(1X,'FIRST',I4,' AT ',I4)
5 CONTINUE
END </langsyntaxhighlight>
{{out}}
<pre>
Line 2,791:
</pre>
===Fortran 90===
<langsyntaxhighlight lang="fortran"> ! Stern-Brocot sequence - Fortran 90
parameter (nn=2400)
dimension isb(nn)
Line 2,812:
write(*,"(1x,'First',i4,' at ',i4)") jj,i
end do
end </langsyntaxhighlight>
{{out}}
<pre>
Line 2,831:
 
=={{header|FreeBASIC}}==
<langsyntaxhighlight lang="freebasic">' version 02-03-2019
' compile with: fbc -s console
 
Line 2,912:
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,932:
 
=={{header|Go}}==
<langsyntaxhighlight lang="go">package main
 
import (
Line 2,979:
}
return x
}</langsyntaxhighlight>
<langsyntaxhighlight lang="go">// SB implements the Stern-Brocot sequence.
//
// Generator() satisfies RC Task 1. For remaining tasks, Generator could be
Line 3,053:
}
}
}</langsyntaxhighlight>
{{out}}
<pre>
Line 3,095:
 
=={{header|Haskell}}==
<langsyntaxhighlight lang="haskell">import Data.List (elemIndex)
 
sb :: [Int]
Line 3,111:
print $
all (\(a, b) -> 1 == gcd a b) $
take 1000 $ zip sb (tail sb)</langsyntaxhighlight>
{{out}}
<pre>[1,1,2,1,3,2,3,1,4,3,5,2,5,3,4]
Line 3,119:
Or, expressed in terms of iterate:
 
<langsyntaxhighlight lang="haskell">import Data.Function (on)
import Data.List (nubBy, sortOn)
import Data.Ord (comparing)
Line 3,146:
print $
(all ((1 ==) . uncurry gcd) . (zip <*> tail)) $
take 1000 sternBrocot</langsyntaxhighlight>
{{Out}}
<pre>[1,1,2,1,3,2,3,1,4,3,5,2,5,3,4]
Line 3,157:
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 3,164:
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 3,170:
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 3,224:
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 3,242:
=== Stern-Brocot Tree ===
{{works with|Java|8}}
<langsyntaxhighlight lang="java">import java.awt.*;
import javax.swing.*;
 
Line 3,304:
});
}
}</langsyntaxhighlight>
[[File:stern_brocot_tree_java.gif]]
 
=={{header|JavaScript}}==
<langsyntaxhighlight JavaScriptlang="javascript">(() => {
'use strict';
 
Line 3,632:
// MAIN ---
return main();
})();</langsyntaxhighlight>
{{Out}}
<pre>[1,1,2,1,3,2,3,1,4,3,5,2,5,3,4]
Line 3,644:
 
'''Foundations:'''
<langsyntaxhighlight lang="jq">def until(cond; update):
def _until:
if cond then . else (update | _until) end;
Line 3,655:
else [.[1], .[0] % .[1]] | rgcd
end;
[a,b] | rgcd ;</langsyntaxhighlight>
'''The A002487 integer sequence:'''
 
Line 3,662:
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 3,679:
| 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 3,712:
"",
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 3,746:
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}
Line 3,775:
else
println("Rejected.")
end</langsyntaxhighlight>
 
{{out}}
Line 3,798:
 
=={{header|Kotlin}}==
<langsyntaxhighlight lang="scala">// version 1.1.0
 
val sbs = mutableListOf(1, 1)
Line 3,861:
}
println("all one")
}</langsyntaxhighlight>
 
{{out}}
Line 3,886:
 
=={{header|Lua}}==
<langsyntaxhighlight Lualang="lua">-- Task 1
function sternBrocot (n)
local sbList, pos, c = {1, 1}, 2
Line 3,934:
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,956:
=={{header|MAD}}==
 
<langsyntaxhighlight MADlang="mad"> NORMAL MODE IS INTEGER
VECTOR VALUES FRST15 = $20HFIRST 15 NUMBERS ARE*$
VECTOR VALUES FRSTAT = $6HFIRST ,I3,S1,11HAPPEARS AT ,I4*$
Line 3,986:
SCAN WHENEVER N .E. STERN(K), FUNCTION RETURN K
END OF FUNCTION
END OF PROGRAM</langsyntaxhighlight>
 
{{out}}
Line 4,019:
 
=={{header|Mathematica}} / {{header|Wolfram Language}}==
<langsyntaxhighlight Mathematicalang="mathematica">sb = {1, 1};
Do[
sb = sb~Join~{Total@sb[[i - 1 ;; i]], sb[[i]]}
Line 4,028:
Flatten[FirstPosition[sb, #] & /@ Range[10]]
First@FirstPosition[sb, 100]
AllTrue[Partition[Take[sb, 1000], 2, 1], Apply[GCD] /* EqualTo[1]]</langsyntaxhighlight>
{{out}}
<pre>{1, 1, 2, 1, 3, 2, 3, 1, 4, 3, 5, 2, 5, 3, 4}
Line 4,036:
 
=={{header|Modula-2}}==
<langsyntaxhighlight lang="modula2">MODULE SternBrocot;
FROM InOut IMPORT WriteString, WriteCard, WriteLn;
 
Line 4,110:
WriteString("The GCD of every pair of adjacent elements is 1.");
WriteLn;
END SternBrocot.</langsyntaxhighlight>
{{out}}
<pre>First 15 numbers: 1 1 2 1 3 2 3 1 4 3 5 2 5 3 4
Line 4,130:
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.
 
<langsyntaxhighlight Nimlang="nim">import math, strformat, strutils
 
iterator sternBrocot(): (int, int) =
Line 4,186:
echo "Found two successive terms at index: ", index
else:
echo "All consecutive terms up to the 1000th member have a GCD equal to one."</langsyntaxhighlight>
 
{{out}}
Line 4,207:
=={{header|Oforth}}==
 
<langsyntaxhighlight Oforthlang="oforth">: stern(n)
| l i |
ListBuffer new dup add(1) dup add(1) dup ->l
Line 4,213:
n 2 mod ifFalse: [ dup removeLast drop ] dup freeze ;
 
stern(10000) Constant new: Sterns</langsyntaxhighlight>
 
{{out}}
Line 4,244:
{{Works with|PARI/GP|2.7.4 and above}}
 
<langsyntaxhighlight lang="parigp">
\\ Stern-Brocot sequence
\\ 5/27/16 aev
Line 4,272:
if(j==1, print("Yes"), print("No"));
}
</langsyntaxhighlight>
{{Output}}
Line 4,284:
=={{header|Pascal}}==
{{works with|Free Pascal}}
<langsyntaxhighlight lang="pascal">program StrnBrCt;
{$IFDEF FPC}
{$MODE DELPHI}
Line 4,370:
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 4,376:
 
=={{header|Perl}}==
<langsyntaxhighlight lang="perl">use strict;
use warnings;
 
Line 4,411:
($a, $b) = ($b, $generator->());
}
}</langsyntaxhighlight>
{{out}}
<pre>1 1 2 1 3 2 3 1 4 3 5 2 5 3 4
Line 4,427:
 
A slightly different method:{{libheader|ntheory}}
<langsyntaxhighlight lang="perl">use ntheory qw/gcd vecsum vecfirst/;
 
sub stern_diatomic {
Line 4,445:
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 4,453:
 
=={{header|Phix}}==
<!--<langsyntaxhighlight Phixlang="phix">(phixonline)-->
<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,495:
<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>
<!--</langsyntaxhighlight>-->
{{Out}}
<pre>
Line 4,507:
{{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 4,523:
(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 4,542:
 
=={{header|PL/I}}==
<langsyntaxhighlight lang="pli">sternBrocot: procedure options(main);
%replace MAX by 1200;
declare S(1:MAX) fixed;
Line 4,589:
end;
put skip list('All GCDs of adjacent pairs are 1.');
end sternBrocot;</langsyntaxhighlight>
{{out}}
<pre>First 15 elements: 1 1 2 1 3 2 3 1 4 3 5 2 5 3 4
Line 4,606:
 
=={{header|PL/M}}==
<langsyntaxhighlight lang="plm">100H:
/* FIND LOCATION OF FIRST ELEMENT IN ARRAY */
FIND$FIRST: PROCEDURE (ARR, EL) ADDRESS;
Line 4,693:
CALL PRINT(.'ALL GCDS ARE 1$');
CALL BDOS(0,0);
EOF</langsyntaxhighlight>
{{out}}
<pre>FIRST 15 ELEMENTS: 1 1 2 1 3 2 3 1 4 3 5 2 5 3 4
Line 4,710:
 
=={{header|PowerShell}}==
<syntaxhighlight lang="powershell">
<lang PowerShell>
# An iterative approach
function iter_sb($count = 2000)
Line 4,739:
'GCD = 1 for first 1000 members: {0}' -f $gcd
}
</syntaxhighlight>
</lang>
 
{{out}}
Line 4,774:
 
=={{header|PureBasic}}==
<langsyntaxhighlight PureBasiclang="purebasic">EnableExplicit
Define.i i
 
Line 4,824:
EndIf
 
Input()</langsyntaxhighlight>
{{out}}
<pre>Stern-Brocot_sequence
Line 4,845:
=={{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 4,880:
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 4,903:
 
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 4,924:
>>> all(gcd(p, t) == 1 for p, t in islice(zip(prev, this), 1000))
True
>>> </langsyntaxhighlight>
 
===Python: Composing pure (curried) functions===
Line 4,930:
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
Line 5,107:
# MAIN ---
if __name__ == '__main__':
main()</langsyntaxhighlight>
{{Out}}
<pre>[1, 1, 2, 1, 3, 2, 3, 1, 4, 3, 5, 2, 5, 3, 4]
Line 5,116:
=={{header|Quackery}}==
 
<langsyntaxhighlight Quackerylang="quackery"> [ [ dup while
tuck mod again ]
drop abs ] is gcd ( n n --> n )
Line 5,142:
[ say "Reducible pair found." ]
else
[ say "No reducible pairs found." ]</langsyntaxhighlight>
 
{{out}}
Line 5,158:
{{libheader|pracma}}
 
<langsyntaxhighlight lang="rsplus">
## Stern-Brocot sequence
## 12/19/16 aev
Line 5,181:
if(j==1) {cat(" *** All GCDs=1!\n")} else {cat(" *** All GCDs!=1??\n")}
}
</langsyntaxhighlight>
 
{{Output}}
Line 5,199:
 
As with the previous solution, we have used a library for our gcd function. In this case, we have used gmp.
<langsyntaxhighlight lang="rsplus">genNStern <- function(n)
{
sternNums <- c(1, 1)
Line 5,219:
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)
Line 5,231:
=={{header|Racket}}==
 
<langsyntaxhighlight lang="racket">#lang racket
;; OEIS Definition
;; A002487
Line 5,268:
(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 5,294:
(formerly Perl 6)
{{works with|rakudo|2017-03}}
<syntaxhighlight lang="raku" perl6line>constant @Stern-Brocot = 1, 1, { |(@_[$_ - 1] + @_[$_], @_[$_]) given ++$ } ... *;
 
put @Stern-Brocot[^15];
Line 5,302:
}
 
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
Line 5,319:
 
=={{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 /*Not specified? Then use the default.*/
Line 5,368:
end /*k*/
if f==0 then return subword($, 1, h)
return $</langsyntaxhighlight>
{{out|output|text=&nbsp; when using the default inputs:}}
<pre>
Line 5,394:
 
=={{header|Ring}}==
<langsyntaxhighlight lang="ring">
# Project : Stern-Brocot sequence
 
Line 5,448:
end
return gcd
</syntaxhighlight>
</lang>
Output:
<pre>
Line 5,468:
=={{header|Ruby}}==
{{works with|Ruby|2.1}}
<langsyntaxhighlight lang="ruby">def sb
return enum_for :sb unless block_given?
a=[1,1]
Line 5,487:
else
puts "Whoops, not all GCD's are 1!"
end</langsyntaxhighlight>
 
{{out}}
Line 5,507:
 
=={{header|Scala}}==
<langsyntaxhighlight lang="scala">lazy val sbSeq: Stream[BigInt] = {
BigInt("1") #::
BigInt("1") #::
Line 5,525:
(sbSeq zip sbSeq.tail).take(1000).forall{ case (a,b) => a.gcd(b) == 1 } )
}
</syntaxhighlight>
</lang>
 
{{out}}
Line 5,548:
{{works with|Chez Scheme}}
'''The Function'''
<langsyntaxhighlight lang="scheme">; Recursive function to return the Nth Stern-Brocot sequence number.
 
(define stern-brocot
Line 5,561:
(else
(let ((earlier (/ (1+ n) 2)))
(+ (stern-brocot earlier) (stern-brocot (1- earlier))))))))</langsyntaxhighlight>
'''The Task'''
<langsyntaxhighlight lang="scheme">; Show the first 15 Stern-Brocot sequence numbers.
 
(printf "First 15 Stern-Brocot numbers:")
Line 5,610:
(set! any-bad #t))))
(when (not any-bad)
(printf "GCDs of all Stern-Brocot consecutive pairs from 1 to 1000 are 1~%")))</langsyntaxhighlight>
{{out}}
<pre>First 15 Stern-Brocot numbers: 1 1 2 1 3 2 3 1 4 3 5 2 5 3 4
Line 5,619:
=={{header|Sidef}}==
{{trans|Perl}}
<langsyntaxhighlight lang="ruby"># Declare a function to generate the Stern-Brocot sequence
func stern_brocot {
var list = [1, 1]
Line 5,652:
} * 1000
 
say "All GCD's are 1"</langsyntaxhighlight>
{{out}}
<pre>
Line 5,672:
=={{header|Snobol}}==
 
<langsyntaxhighlight lang="snobol">* GCD function
DEFINE('GCD(A,B)') :(GCD_END)
GCD GCD = A
Line 5,716:
GCDFAIL OUTPUT = "GCD is not 1 at " IX "."
 
END</langsyntaxhighlight>
 
{{out}}
Line 5,737:
=={{header|Swift}}==
 
<langsyntaxhighlight lang="swift">struct SternBrocot: Sequence, IteratorProtocol {
private var seq = [1, 1]
 
Line 5,776:
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 5,794:
 
=={{header|Tcl}}==
<langsyntaxhighlight lang="tcl">
#!/usr/bin/env tclsh
#
Line 5,899:
 
main
</syntaxhighlight>
</lang>
{{Out}}
<pre>
Line 5,922:
 
=={{header|VBScript}}==
<langsyntaxhighlight VBScriptlang="vbscript">sb = Array(1,1)
i = 1 'considered
j = 2 'precedent
Line 5,961:
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 5,978:
=={{header|Visual Basic .NET}}==
{{trans|C#}}
<langsyntaxhighlight lang="vbnet">Imports System
Imports System.Collections.Generic
Imports System.Linq
Line 6,006:
" 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 6,030:
{{libheader|Wren-math}}
{{libheader|Wren-fmt}}
<langsyntaxhighlight lang="ecmascript">import "/math" for Int
import "/fmt" for Fmt
 
Line 6,102:
p = p + 2
}
System.print("all one.")</langsyntaxhighlight>
 
{{out}}
Line 6,127:
 
=={{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 6,137:
[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>
10,327

edits