2016 Update

This commit is contained in:
Tina Müller 2016-12-05 22:15:40 +01:00
parent 948b86eafa
commit dcf5d15da3
7965 changed files with 139854 additions and 31002 deletions

View file

@ -1,35 +1,40 @@
For this task, the Stern-Brocot sequence is to be generated by an algorithm similar to that employed in generating the [[Fibonacci sequence]].
# The first and second members of the sequence are both 1:
#* 1, 1
#*     1, 1
# Start by considering the second member of the sequence
# Sum the considered member of the sequence and its precedent, (1 + 1) = 2, and append it to the end of the sequence:
#* 1, 1, 2
#*     1, 1, 2
# Append the considered member of the sequence to the end of the sequence:
#* 1, 1, 2, 1
#*     1, 1, 2, 1
# Consider the next member of the series, (the third member i.e. 2)
# GOTO 3
#*
#*         ─── Expanding another loop we get: ───
#*
# Sum the considered member of the sequence and its precedent, (2 + 1) = 3, and append it to the end of the sequence:
#*     1, 1, 2, 1, 3
# Append the considered member of the sequence to the end of the sequence:
#*     1, 1, 2, 1, 3, 2
# Consider the next member of the series, (the fourth member i.e. 1)
Expanding another loop we get:
7. Sum the considered member of the sequence and its precedent, (2 + 1) = 3, and append it to the end of the sequence:
* 1, 1, 2, 1, 3
8. Append the considered member of the sequence to the end of the sequence:
* 1, 1, 2, 1, 3, 2
9. Consider the next member of the series, (the fourth member i.e. 1)
;The task is to:
# Create a function/method/subroutine/procedure/... to generate the Stern-Brocot sequence of integers using the method outlined above.
# Show the first fifteen members of the sequence. (This should be: 1, 1, 2, 1, 3, 2, 3, 1, 4, 3, 5, 2, 5, 3, 4)
# Show the (1-based) index of where the numbers 1-to-10 first appears in the sequence.
# Show the (1-based) index of where the number 100 first appears in the sequence.
# Check that the greatest common divisor of all the two consecutive members of the series up to the 1000th member, is always one.
Show your output on the page.
* Create a function/method/subroutine/procedure/... to generate the Stern-Brocot sequence of integers using the method outlined above.
* Show the first fifteen members of the sequence. (This should be: 1, 1, 2, 1, 3, 2, 3, 1, 4, 3, 5, 2, 5, 3, 4)
* Show the (1-based) index of where the numbers 1-to-10 first appears in the sequence.
* Show the (1-based) index of where the number 100 first appears in the sequence.
* Check that the greatest common divisor of all the two consecutive members of the series up to the 1000<sup>th</sup> member, is always one.
<br>Show your output on this page.
;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.
;Related Tasks:
* [[Continued fraction/Arithmetic]]
<br><br>

View file

@ -0,0 +1,77 @@
Found := FindOneToX(100), FoundList := ""
Loop, 10
FoundList .= "First " A_Index " found at " Found[A_Index] "`n"
MsgBox, 64, Stern-Brocot Sequence
, % "First 15: " FirstX(15) "`n"
. FoundList
. "First 100 found at " Found[100] "`n"
. "GCDs of all two consecutive members are " (GCDsUpToXAreOne(1000) ? "" : "not ") "one."
return
class SternBrocot
{
__New()
{
this[1] := 1
this[2] := 1
this.Consider := 2
}
InsertPair()
{
n := this.Consider
this.Push(this[n] + this[n - 1], this[n])
this.Consider++
}
}
; 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)
FirstX(x)
{
SB := new SternBrocot()
while SB.MaxIndex() < x
SB.InsertPair()
Loop, % x
Out .= SB[A_Index] ", "
return RTrim(Out, " ,")
}
; Show the (1-based) index of where the numbers 1-to-10 first appears in the sequence.
; Show the (1-based) index of where the number 100 first appears in the sequence.
FindOneToX(x)
{
SB := new SternBrocot(), xRequired := x, Found := []
while xRequired > 0 ; While the count of numbers yet to be found is > 0.
{
Loop, 2 ; Consider the second last member and then the last member.
{
n := SB[i := SB.MaxIndex() - 2 + A_Index]
; If number (n) has not been found yet, and it is less than the maximum number to
; find (x), record the index (i) and decrement the count of numbers yet to be found.
if (Found[n] = "" && n <= x)
Found[n] := i, xRequired--
}
SB.InsertPair() ; Insert the two members that will be checked next.
}
return Found
}
; Check that the greatest common divisor of all the two consecutive members of the series up to
; the 1000th member, is always one.
GCDsUpToXAreOne(x)
{
SB := new SternBrocot()
while SB.MaxIndex() < x
SB.InsertPair()
Loop, % x - 1
if GCD(SB[A_Index], SB[A_Index + 1]) > 1
return 0
return 1
}
GCD(a, b) {
while b
b := Mod(a | 0x0, a := b)
return a
}

View file

@ -0,0 +1,32 @@
(ns test-p.core)
(defn gcd
"(gcd a b) computes the greatest common divisor of a and b."
[a b]
(if (zero? b)
a
(recur b (mod a b))))
(defn stern-brocat-next [p]
" p is the block of the sequence we are using to compute the next block
This routine computes the next block "
(into [] (concat (rest p) [(+ (first p) (second p))] [(second p)])))
(defn seq-stern-brocat
([] (seq-stern-brocat [1 1]))
([p] (lazy-seq (cons (first p)
(seq-stern-brocat (stern-brocat-next p))))))
; First 15 elements
(println (take 15 (seq-stern-brocat)))
; Where numbers 1 to 10 first appear
(doseq [n (concat (range 1 11) [100])]
(println "The first appearnce of" n "is at index" (some (fn [[i k]] (when (= k n) (inc i)))
(map-indexed vector (seq-stern-brocat)))))
;; Check that gcd between 1st 1000 consecutive elements equals 1
; Create cosecutive pairs of 1st 1000 elements
(def one-thousand-pairs (take 1000 (partition 2 1 (seq-stern-brocat))))
; Check every pair has a gcd = 1
(println (every? (fn [[ith ith-plus-1]] (= (gcd ith ith-plus-1) 1))
one-thousand-pairs))

View file

@ -0,0 +1,28 @@
defmodule SternBrocot do
def sequence do
Stream.unfold({0,{1,1}}, fn {i,acc} ->
a = elem(acc, i)
b = elem(acc, i+1)
{a, {i+1, Tuple.append(acc, a+b) |> Tuple.append(b)}}
end)
end
def task do
IO.write "First fifteen members of the sequence:\n "
IO.inspect Enum.take(sequence, 15)
Enum.each(Enum.concat(1..10, [100]), fn n ->
i = Enum.find_index(sequence, &(&1==n)) + 1
IO.puts "#{n} first appears at #{i}"
end)
Enum.take(sequence, 1000)
|> Enum.chunk(2,1)
|> Enum.all?(fn [a,b] -> gcd(a,b) == 1 end)
|> if(do: "All GCD's are 1", else: "Whoops, not all GCD's are 1!")
|> IO.puts
end
defp gcd(a,0), do: abs(a)
defp gcd(a,b), do: gcd(b, rem(a,b))
end
SternBrocot.task

View file

@ -0,0 +1,63 @@
import java.awt.*;
import javax.swing.*;
public class SternBrocot extends JPanel {
public SternBrocot() {
setPreferredSize(new Dimension(800, 500));
setFont(new Font("Arial", Font.PLAIN, 18));
setBackground(Color.white);
}
private void drawTree(int n1, int d1, int n2, int d2,
int x, int y, int gap, int lvl, Graphics2D g) {
if (lvl == 0)
return;
// mediant
int numer = n1 + n2;
int denom = d1 + d2;
if (lvl > 1) {
g.drawLine(x + 5, y + 4, x - gap + 5, y + 124);
g.drawLine(x + 5, y + 4, x + gap + 5, y + 124);
}
g.setColor(getBackground());
g.fillRect(x - 10, y - 15, 35, 40);
g.setColor(getForeground());
g.drawString(String.valueOf(numer), x, y);
g.drawString("_", x, y + 2);
g.drawString(String.valueOf(denom), x, y + 22);
drawTree(n1, d1, numer, denom, x - gap, y + 120, gap / 2, lvl - 1, g);
drawTree(numer, denom, n2, d2, x + gap, y + 120, gap / 2, lvl - 1, g);
}
@Override
public void paintComponent(Graphics gg) {
super.paintComponent(gg);
Graphics2D g = (Graphics2D) gg;
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
int w = getWidth();
drawTree(0, 1, 1, 0, w / 2, 50, w / 4, 4, g);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
JFrame f = new JFrame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setTitle("Stern-Brocot Tree");
f.setResizable(false);
f.add(new SternBrocot(), BorderLayout.CENTER);
f.pack();
f.setLocationRelativeTo(null);
f.setVisible(true);
});
}
}

View file

@ -0,0 +1,49 @@
-- Task 1
function sternBrocot (n)
local sbList, pos, c = {1, 1}, 2
repeat
c = sbList[pos]
table.insert(sbList, c + sbList[pos - 1])
table.insert(sbList, c)
pos = pos + 1
until #sbList >= n
return sbList
end
-- Return index in table 't' of first value matching 'v'
function findFirst (t, v)
for key, value in pairs(t) do
if v then
if value == v then return key end
else
if value ~= 0 then return key end
end
end
return nil
end
-- Return greatest common divisor of 'x' and 'y'
function gcd (x, y)
if y == 0 then
return math.abs(x)
else
return gcd(y, x % y)
end
end
-- Check GCD of adjacent values in 't' up to 1000 is always 1
function task5 (t)
for pos = 1, 1000 do
if gcd(t[pos], t[pos + 1]) ~= 1 then return "FAIL" end
end
return "PASS"
end
-- Main procedure
local sb = sternBrocot(10000)
io.write("Task 2: ")
for n = 1, 15 do io.write(sb[n] .. " ") end
print("\n\nTask 3:")
for i = 1, 10 do print("\t" .. i, findFirst(sb, i)) end
print("\nTask 4: " .. findFirst(sb, 100))
print("\nTask 5: " .. task5(sb))

View file

@ -0,0 +1,27 @@
\\ Stern-Brocot sequence
\\ 5/27/16 aev
SternBrocot(n)={
my(L=List([1,1]),k=2); if(n<3,return(L));
for(i=2,n, listput(L,L[i]+L[i-1]); if(k++>=n, break); listput(L,L[i]);if(k++>=n, break));
return(Vec(L));
}
\\ Find the first item in any list starting with sind index (return 0 or index).
\\ 9/11/2015 aev
findinlist(list, item, sind=1)={
my(idx=0, ln=#list); if(ln==0 || sind<1 || sind>ln, return(0));
for(i=sind, ln, if(list[i]==item, idx=i; break;)); return(idx);
}
{
\\ Required tests:
my(v,j);
v=SternBrocot(15);
print1("The first 15: "); print(v);
v=SternBrocot(1200);
print1("The first i@n: "); \\print(v);
for(i=1,10, if(j=findinlist(v,i), print1(i,"@",j,", ")));
if(j=findinlist(v,100), print(100,"@",j));
v=SternBrocot(10000);
print1("All GCDs=1?: ");
j=1; for(i=2,10000, j*=gcd(v[i-1],v[i]));
if(j==1, print("Yes"), print("No"));
}

View file

@ -0,0 +1,87 @@
program StrnBrCt;
{$IFDEF FPC}
{$MODE DELPHI}
{$ENDIF}
const
MaxCnt = 10835282;{ seq[i] < 65536 = high(Word) }
//MaxCnt = 500*1000*1000;{ 2Gbyte -> real 0.85 s user 0.31 }
type
tSeqdata = word;//cardinal LongWord
pSeqdata = pWord;//pcardinal pLongWord
tseq = array of tSeqdata;
function SternBrocotCreate(size:NativeInt):tseq;
var
pSeq,pIns : pSeqdata;
PosIns : NativeInt;
sum : tSeqdata;
Begin
setlength(result,Size+1);
dec(Size); //== High(result)
pIns := @result[size];// set at end
PosIns := -size+2; // negative index campare to 0
pSeq := @result[0];
sum := 1;
pSeq[0]:= sum;pSeq[1]:= sum;
repeat
pIns[PosIns+1] := sum;//append copy of considered
inc(sum,pSeq[0]);
pIns[PosIns ] := sum;
inc(pSeq);
inc(PosIns,2);sum := pSeq[1];//aka considered
until PosIns>= 0;
setlength(result,length(result)-1);
end;
function FindIndex(const s:tSeq;value:tSeqdata):NativeInt;
Begin
result := 0;
while result <= High(s) do
Begin
if s[result] = value then
EXIT(result+1);
inc(result);
end;
end;
function gcd_iterative(u, v: NativeInt): NativeInt;
//http://rosettacode.org/wiki/Greatest_common_divisor#Pascal_.2F_Delphi_.2F_Free_Pascal
var
t: NativeInt;
begin
while v <> 0 do begin
t := u;u := v;v := t mod v;
end;
gcd_iterative := abs(u);
end;
var
seq : tSeq;
i : nativeInt;
Begin
seq:= SternBrocotCreate(MaxCnt);
// Show the first fifteen members of the sequence.
For i := 0 to 13 do write(seq[i],',');writeln(seq[14]);
//Show the (1-based) index of where the numbers 1-to-10 first appears in the
For i := 1 to 10 do
write(i,' @ ',FindIndex(seq,i),',');
writeln(#8#32);
//Show the (1-based) index of where the number 100 first appears in the sequence.
writeln(100,' @ ',FindIndex(seq,100));
//Check that the greatest common divisor of all the two consecutive members of the series up to the 1000th member, is always one.
i := 999;
if i > High(seq) then
i := High(seq);
Repeat
IF gcd_iterative(seq[i],seq[i+1]) <>1 then
Begin
writeln(' failure at ',i+1,' ',seq[i],' ',seq[i+1]);
BREAK;
end;
dec(i);
until i <0;
IF i< 0 then
writeln('GCD-test is O.K.');
setlength(seq,0);
end.

View file

@ -6,7 +6,7 @@ constant Stern-Brocot = flat
say Stern-Brocot[^15];
for 1 .. 10, 100 -> $ix {
say "first occurrence of $ix is at index : ", 1 + Stern-Brocot.first-index($ix);
say "first occurrence of $ix is at index : ", 1 + Stern-Brocot.first($ix, :k);
}
say so 1 == all map ^1000: { [gcd] Stern-Brocot[$_, $_ + 1] }

View file

@ -0,0 +1,28 @@
# An iterative approach
function iter_sb($count = 2000)
{
# Taken from RosettaCode GCD challenge
function Get-GCD ($x, $y)
{
if ($y -eq 0) { $x } else { Get-GCD $y ($x%$y) }
}
$answer = @(1,1)
$index = 1
while ($answer.Length -le $count)
{
$answer += $answer[$index] + $answer[$index - 1]
$answer += $answer[$index]
$index++
}
0..14 | foreach {$answer[$_]}
1..10 | foreach {'Index of {0}: {1}' -f $_, ($answer.IndexOf($_) + 1)}
'Index of 100: {0}' -f ($answer.IndexOf(100) + 1)
[bool] $gcd = $true
1..999 | foreach {$gcd = $gcd -and ((Get-GCD $answer[$_] $answer[$_ - 1]) -eq 1)}
'GCD = 1 for first 1000 members: {0}' -f $gcd
}

View file

@ -1,45 +1,44 @@
/*REXX program gens/shows 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 /* N defined? Then use the default. */
if idx=='' | idx==',' then idx= 10 /*IDX " " " " " */
if fix=='' | fix==',' then fix= 100 /*FIX " " " " " */
if chk=='' | chk==',' then chk=1000 /*CHK " " " " " */
/*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 /* N not defined? Then use default.*/
if idx=='' | idx=="," then idx= 10 /*IDX " " " " " */
if fix=='' | fix=="," then fix= 100 /*FIX " " " " " */
if chk=='' | chk=="," then chk=1000 /*CHK " " " " " */
say center('the first' N 'numbers in the SternBrocot sequence', 70, '')
a=Stern_Brocot(N) /*invoke function to generate sequence.*/
say a /*display the sequence to the terminal.*/
say; say center('the 1-based index for the first' idx "integers",70,'')
a=Stern_Brocot(-idx) /*invoke function to generate sequence.*/
do i=1 for idx
say 'for ' right(i,length(idx))", the index is: " wordpos(i,a)
end /*i*/
say; say center('the 1-based index for' fix,70,'')
a=Stern_Brocot(-fix) /*invoke function to generate sequence.*/
say center('the first' N "numbers in the Stern─Brocot sequence", 70, '')
a=Stern_Brocot(N) /*invoke function to generate sequence.*/
say a /*display the sequence to the terminal.*/
say
say center('the 1-based index for the first' idx "integers", 70, '')
a=Stern_Brocot(-idx) /*invoke function to generate sequence.*/
do i=1 for idx
say 'for ' right(i,length(idx))", the index is: " wordpos(i,a)
end /*i*/
say
say center('the 1-based index for' fix, 70, "")
a=Stern_Brocot(-fix) /*invoke function to generate sequence.*/
say 'for ' fix", the index is: " wordpos(fix, a)
say
say center('checking if all two consecutive members have a GCD=1', 70, '')
a=Stern_Brocot(chk) /*invoke function to generate sequence.*/
do c=1 for chk-1; if gcd(subword(a,c,2))==1 then iterate
say 'GCD check failed at member' c"."; exit 13
end /*c*/
say; say center('checking if all two consecutive members have a GCD=1',70,'')
a=Stern_Brocot(chk) /*invoke function to generate sequence.*/
do c=1 for chk-1; if gcd(subword(a,c,2))==1 then iterate
say 'GCD check failed at member' c"."; exit 13
end /*c*/
say ' All ' chk " two consecutive members have a GCD of unity."
exit /*stick a fork in it, we're all done. */
/*────────────────────────────────────────────────────────────────────────────*/
gcd: procedure; $=; do i=1 for arg(); $=$ arg(i); end /*arg list*/
parse var $ x z .; if x=0 then x=z /*handle special 0 case.*/
x=abs(x)
do j=2 to words($); y=abs(word($,j)); if y=0 then iterate
do until y==0; parse value x//y y with y x; end /*◄──heavy lifting*/
end /*j*/
return x
/*────────────────────────────────────────────────────────────────────────────*/
Stern_Brocot: parse arg h 1 f; $=1 1; if h<0 then h=1e9
else f=0; f=abs(f)
do k=2 until words($)>=h; _=word($,k); $=$ (_+word($,k-1)) _
if f==0 then iterate; if wordpos(f,$)\==0 then leave
end /*until*/
if f==0 then return subword($,1,h)
return $
exit /*stick a fork in it, we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
gcd: procedure; $=; do i=1 for arg(); $=$ arg(i); end /*i*/ /*arg list. */
parse var $ x z .; if x=0 then x=z; x=abs(x) /*zero case?*/
do j=2 to words($); y=abs(word($,j)); if y=0 then iterate /*ignore 0's*/
do until y==0; parse value x//y y with y x; end /*heavy work*/
end /*j*/
return x /*return GCD*/
/*──────────────────────────────────────────────────────────────────────────────────────*/
Stern_Brocot: parse arg h 1 f; $=1 1; if h<0 then h=1e9
else f=0; f=abs(f)
do k=2 until words($)>=h | wordpos(f,$)\==0
_=word($,k); $=$ (_+word($,k-1)) _; if f==0 then iterate
end /*until*/
if f==0 then return subword($,1,h)
return $

View file

@ -0,0 +1,18 @@
lazy val sbSeq: Stream[BigInt] = {
BigInt("1") #::
BigInt("1") #::
(sbSeq zip sbSeq.tail zip sbSeq.tail).
flatMap{ case ((a,b),c) => List(a+b,c) }
}
// Show the results
{
println( s"First 15 members: ${(for( n <- 0 until 15 ) yield sbSeq(n)) mkString( "," )}" )
println
for( n <- 1 to 10; pos = sbSeq.indexOf(n) + 1 ) println( s"Position of first $n is at $pos" )
println
println( s"Position of first 100 is at ${sbSeq.indexOf(100) + 1}" )
println
println( s"Greatest Common Divisor for first 1000 members is 1: " +
(sbSeq zip sbSeq.tail).take(1000).forall{ case (a,b) => a.gcd(b) == 1 } )
}