Stern-Brocot sequence: Difference between revisions
m
syntax highlighting fixup automation
(Added Quackery.) |
Thundergnat (talk | contribs) m (syntax highlighting fixup automation) |
||
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}}==
<
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</
{{out}}
Line 346:
=={{header|8086 Assembly}}==
<
cpu 8086
bits 16
Line 446:
numbuf: db ' $'
nl: db 13,10,'$'
seq: db 1,1</
{{out}}
Line 458:
=={{header|Action!}}==
<
INT i
Line 533:
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 557:
=={{header|Ada}}==
<
procedure Sequence is
Line 650:
when Constraint_Error => Put_Line("Some GCD > 1; this is wrong!!!") ;
end;
end Sequence;</
{{out}}
Line 661:
=={{header|ALGOL 68}}==
<
# 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</
{{out}}
<pre>
Line 748:
=={{header|ALGOL-M}}==
<
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</
{{out}}
<pre>First 15 numbers:
Line 819:
=={{header|Amazing Hopper}}==
Version: hopper-FLOW!:
<syntaxhighlight lang="amazing hopper">
#include <flow.h>
#include <flow-flow.h>
Line 857:
NEXT
RET
</syntaxhighlight>
{{out}}
<pre>
Line 877:
=={{header|APL}}==
<
stern←{⍵{
⍺←0 ⋄ ⍺⍺≤⍴⍵:⍺⍺↑⍵
Line 887:
⎕←'Location of 100:',seq⍳100
⎕←'All GCDs 1:','no' 'yes'[1+1∧.=2∨/1000↑seq]
}</
{{out}}
Line 897:
=={{header|AppleScript}}==
<
use framework "Foundation"
use scripting additions
Line 1,437:
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,445:
=={{header|AutoHotkey}}==
<
Loop, 10
FoundList .= "First " A_Index " found at " Found[A_Index] "`n"
Line 1,521:
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,539:
=={{header|BASIC}}==
<
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</
{{out}}
Line 1,581:
==={{header|BASIC256}}===
{{trans|FreeBASIC}}
<
max = 2000
global stern
Line 1,643:
else
print "The GCD for index "; i; " and "; i+1; " = "; d
end if</
{{out}}
<pre>Igual que la entrada de FreeBASIC.</pre>
Line 1,650:
{{trans|FreeBASIC}}
{{works with|QBasic|1.1}}
<
DIM SHARED stern(max + 2)
Line 1,710:
ELSE
PRINT "The GCD for index "; i; " and "; i + 1; " = "; d
END IF</
{{out}}
<pre>Igual que la entrada de FreeBASIC.</pre>
Line 1,716:
==={{header|Yabasic}}===
{{trans|FreeBASIC}}
<
dim stern(limite+2)
Line 1,771:
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,819:
$) 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,839:
=={{header|C}}==
Recursive function.
<
typedef unsigned int uint;
Line 1,876:
return 0;
}</
{{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.
<
{
uint a = 1, b = 0;
Line 1,903:
}
return b;
}</
=={{header|C sharp|C#}}==
<
using System.Collections.Generic;
using System.Linq;
Line 1,931:
" 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,952:
=={{header|C++}}==
<
#include <iostream>
#include <iomanip>
Line 2,003:
return 0;
}
</syntaxhighlight>
{{out}}
<pre>
Line 2,046:
=={{header|Clojure}}==
<
(defn sb-step [v]
(let [i (quot (count v) 2)]
Line 2,079:
true)
(report-sb)</
{{Output}}
Line 2,099:
===Clojure: Using Lazy Sequences===
<
(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>
{{Output}}
Line 2,151:
=={{header|CLU}}==
<
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</
{{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}}==
<
(declare ((or null (vector integer)) numbers))
(cond ((null numbers)
Line 2,273:
(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,290:
=={{header|Cowgol}}==
<
# Redefining these is enough to change the type and length everywhere,
Line 2,366:
end loop;
print("All GCDs are 1.\n");</
{{out}}
Line 2,376:
=={{header|D}}==
{{trans|Python}}
<
/// 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.");
}</
{{out}}
<pre>The first 15 values:
Line 2,422:
This uses a queue from the Queue/usage Task:
<
struct SternBrocot {
Line 2,439:
void main() {
SternBrocot().drop(50_000_000).front.writeln;
}</
{{out}}
<pre>7004</pre>
Line 2,445:
<b>Direct Version:</b>
{{trans|C}}
<
import std.stdio, std.numeric, std.range, std.algorithm, std.bigint, std.conv;
Line 2,472:
sternBrocot(10.BigInt ^^ 20_000).text.length.writeln;
}</
{{out}}
<pre>The first 15 values:
Line 2,492:
=={{header|EchoLisp}}==
=== Function ===
<
;; 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>
{{out}}
<
; generate the sequence and check GCD
(for ((n 10000))
Line 2,525:
(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,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>
=={{header|Elixir}}==
<
def sequence do
Stream.unfold({0,{1,1}}, fn {i,acc} ->
Line 2,574:
end
SternBrocot.task</
{{out}}
Line 2,596:
=={{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,618:
=={{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,648:
: main ( -- ) first15 first-appearances gcd-test ;
MAIN: main</
{{out}}
<pre>
Line 2,668:
=={{header|Forth}}==
<
dup 2 >= if
2 /mod swap if
Line 2,720:
task
bye</
{{out}}
Line 2,742:
{{trans|VBScript}}
===Fortran IV===
<
DIMENSION ISB(2400)
NN=2400
Line 2,772:
103 FORMAT(1X,'FIRST',I4,' AT ',I4)
5 CONTINUE
END </
{{out}}
<pre>
Line 2,791:
</pre>
===Fortran 90===
<
parameter (nn=2400)
dimension isb(nn)
Line 2,812:
write(*,"(1x,'First',i4,' at ',i4)") jj,i
end do
end </
{{out}}
<pre>
Line 2,831:
=={{header|FreeBASIC}}==
<
' compile with: fbc -s console
Line 2,912:
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,932:
=={{header|Go}}==
<
import (
Line 2,979:
}
return x
}</
<
//
// Generator() satisfies RC Task 1. For remaining tasks, Generator could be
Line 3,053:
}
}
}</
{{out}}
<pre>
Line 3,095:
=={{header|Haskell}}==
<
sb :: [Int]
Line 3,111:
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,119:
Or, expressed in terms of iterate:
<
import Data.List (nubBy, sortOn)
import Data.Ord (comparing)
Line 3,146:
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,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:
<
ind=. 0
seq=. 1 1
Line 3,164:
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,170:
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,224:
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,242:
=== Stern-Brocot Tree ===
{{works with|Java|8}}
<
import javax.swing.*;
Line 3,304:
});
}
}</
[[File:stern_brocot_tree_java.gif]]
=={{header|JavaScript}}==
<
'use strict';
Line 3,632:
// MAIN ---
return main();
})();</
{{Out}}
<pre>[1,1,2,1,3,2,3,1,4,3,5,2,5,3,4]
Line 3,644:
'''Foundations:'''
<
def _until:
if cond then . else (update | _until) end;
Line 3,655:
else [.[1], .[0] % .[1]] | rgcd
end;
[a,b] | rgcd ;</
'''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.
<
# 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 ) ;</
'''The tasks:'''
<
def stern_brocot(n): A002487(n+1) | .[1:n+1][];
Line 3,712:
"",
gcd_task
</syntaxhighlight>
{{out}}
<
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</
=={{header|Julia}}==
{{trans|Python}}
<
function sternbrocot(f::Function=(x) -> length(x) ≥ 20)::Vector{Int}
Line 3,775:
else
println("Rejected.")
end</
{{out}}
Line 3,798:
=={{header|Kotlin}}==
<
val sbs = mutableListOf(1, 1)
Line 3,861:
}
println("all one")
}</
{{out}}
Line 3,886:
=={{header|Lua}}==
<
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))</
{{out}}
<pre>Task 2: 1 1 2 1 3 2 3 1 4 3 5 2 5 3 4
Line 3,956:
=={{header|MAD}}==
<
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</
{{out}}
Line 4,019:
=={{header|Mathematica}} / {{header|Wolfram Language}}==
<
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]]</
{{out}}
<pre>{1, 1, 2, 1, 3, 2, 3, 1, 4, 3, 5, 2, 5, 3, 4}
Line 4,036:
=={{header|Modula-2}}==
<
FROM InOut IMPORT WriteString, WriteCard, WriteLn;
Line 4,110:
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,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.
<
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."</
{{out}}
Line 4,207:
=={{header|Oforth}}==
<
| 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</
{{out}}
Line 4,244:
{{Works with|PARI/GP|2.7.4 and above}}
<
\\ Stern-Brocot sequence
\\ 5/27/16 aev
Line 4,272:
if(j==1, print("Yes"), print("No"));
}
</
{{Output}}
Line 4,284:
=={{header|Pascal}}==
{{works with|Free Pascal}}
<
{$IFDEF FPC}
{$MODE DELPHI}
Line 4,370:
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,376:
=={{header|Perl}}==
<
use warnings;
Line 4,411:
($a, $b) = ($b, $generator->());
}
}</
{{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}}
<
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";</
{{out}}
<pre>First fifteen: [1 1 2 1 3 2 3 1 4 3 5 2 5 3 4]
Line 4,453:
=={{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,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>
<!--</
{{Out}}
<pre>
Line 4,507:
{{trans|C}}
Using the <tt>gcd</tt> function defined at ''[[Greatest_common_divisor#PicoLisp]]'':
<
(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!") )</
{{out}}
<pre>
Line 4,542:
=={{header|PL/I}}==
<
%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;</
{{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}}==
<
/* 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</
{{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">
# An iterative approach
function iter_sb($count = 2000)
Line 4,739:
'GCD = 1 for first 1000 members: {0}' -f $gcd
}
</syntaxhighlight>
{{out}}
Line 4,774:
=={{header|PureBasic}}==
<
Define.i i
Line 4,824:
EndIf
Input()</
{{out}}
<pre>Stern-Brocot_sequence
Line 4,845:
=={{header|Python}}==
===Python: procedural===
<
"""\
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'</
{{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'
<
>>> 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
>>> </
===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}}
<
import math
Line 5,107:
# MAIN ---
if __name__ == '__main__':
main()</
{{Out}}
<pre>[1, 1, 2, 1, 3, 2, 3, 1, 4, 3, 5, 2, 5, 3, 4]
Line 5,116:
=={{header|Quackery}}==
<
tuck mod again ]
drop abs ] is gcd ( n n --> n )
Line 5,142:
[ say "Reducible pair found." ]
else
[ say "No reducible pairs found." ]</
{{out}}
Line 5,158:
{{libheader|pracma}}
<
## Stern-Brocot sequence
## 12/19/16 aev
Line 5,181:
if(j==1) {cat(" *** All GCDs=1!\n")} else {cat(" *** All GCDs!=1??\n")}
}
</
{{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.
<
{
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)</
{{Output}}
<pre>> firstFiveThousandTerms <- genNStern(5000)
Line 5,231:
=={{header|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"))</
{{out}}
Line 5,294:
(formerly Perl 6)
{{works with|rakudo|2017-03}}
<syntaxhighlight lang="raku"
put @Stern-Brocot[^15];
Line 5,302:
}
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,319:
=={{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,368:
end /*k*/
if f==0 then return subword($, 1, h)
return $</
{{out|output|text= when using the default inputs:}}
<pre>
Line 5,394:
=={{header|Ring}}==
<
# Project : Stern-Brocot sequence
Line 5,448:
end
return gcd
</syntaxhighlight>
Output:
<pre>
Line 5,468:
=={{header|Ruby}}==
{{works with|Ruby|2.1}}
<
return enum_for :sb unless block_given?
a=[1,1]
Line 5,487:
else
puts "Whoops, not all GCD's are 1!"
end</
{{out}}
Line 5,507:
=={{header|Scala}}==
<
BigInt("1") #::
BigInt("1") #::
Line 5,525:
(sbSeq zip sbSeq.tail).take(1000).forall{ case (a,b) => a.gcd(b) == 1 } )
}
</syntaxhighlight>
{{out}}
Line 5,548:
{{works with|Chez Scheme}}
'''The Function'''
<
(define stern-brocot
Line 5,561:
(else
(let ((earlier (/ (1+ n) 2)))
(+ (stern-brocot earlier) (stern-brocot (1- earlier))))))))</
'''The Task'''
<
(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~%")))</
{{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}}
<
func stern_brocot {
var list = [1, 1]
Line 5,652:
} * 1000
say "All GCD's are 1"</
{{out}}
<pre>
Line 5,672:
=={{header|Snobol}}==
<
DEFINE('GCD(A,B)') :(GCD_END)
GCD GCD = A
Line 5,716:
GCDFAIL OUTPUT = "GCD is not 1 at " IX "."
END</
{{out}}
Line 5,737:
=={{header|Swift}}==
<
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")</
{{out}}
Line 5,794:
=={{header|Tcl}}==
<
#!/usr/bin/env tclsh
#
Line 5,899:
main
</syntaxhighlight>
{{Out}}
<pre>
Line 5,922:
=={{header|VBScript}}==
<
i = 1 'considered
j = 2 'precedent
Line 5,961:
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,978:
=={{header|Visual Basic .NET}}==
{{trans|C#}}
<
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</
{{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}}
<
import "/fmt" for Fmt
Line 6,102:
p = p + 2
}
System.print("all one.")</
{{out}}
Line 6,127:
=={{header|zkl}}==
<
{ 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") }</
{{out}}
<pre>
|