Skip to content

Instantly share code, notes, and snippets.

@sblom
Created April 12, 2012 17:47
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sblom/2369593 to your computer and use it in GitHub Desktop.
Save sblom/2369593 to your computer and use it in GitHub Desktop.
Stern–Brocot generator: generate all positive rational numbers
frac[1] = {{0, 1}, {1, 1}, {1,0}}
frac[n_] := frac[n] = frac[n - 1] ~Riffle~ newFracs[n - 1]
newFracs[n_] := Apply[Plus, #] & /@ Partition[frac[n], 2, 1]
(* Example usage: *)
Map[Apply[Divide, #] &, frac[14]]
(*
A few very surprising things happen here:
1) By the nth generation (i.e. frac[n]), all of the fractions with the denominator N have been generated.
2) It appears that every fraction is always generated in reduced form.
*)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment