Skip to content

Instantly share code, notes, and snippets.

@mat813
Created April 2, 2023 14:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mat813/511970ca8a4ea10013a6dc165e04e65f to your computer and use it in GitHub Desktop.
Save mat813/511970ca8a4ea10013a6dc165e04e65f to your computer and use it in GitHub Desktop.
const farey = (x: number, N: number): [number, number] => {
if (x > 1) {
const units = Math.floor(x);
const [a, d] = farey(x - units, N);
return [a + units * d, d];
}
let [a, b] = [0, 1];
let [c, d] = [1, 1];
while (b <= N && d <= N) {
const mediant = (a + c) / (b + d);
if (x == mediant) {
if (b + d <= N) {
return [a + c, b + d];
} else if (d > b) {
return [c, d];
} else {
return [a, b];
}
} else if (x > mediant) {
[a, b] = [a + c, b + d];
} else {
[c, d] = [a + c, b + d];
}
}
if (b > N) {
return [c, d];
} else {
return [a, b];
}
};
farey(563 / 337, 1000);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment