Stern diatomic / Stern-Brocot sequence
Get any term of Stern's diatomic sequence from its index: s(10) is 3, worked out in whole-number steps that halve the index each time, so even large indices come back exact. Free in your browser.
- Free
- Runs in your browser
- No sign-up
- Your data stays on your device
Run — free
Worked example
- N
- 10
- Stern
- 3
- Recurrence
- s(0)=0; s(1)=1; s(2k)=s(k); s(2k+1)=s(k)+s(k+1)
Stern's diatomic sequence is a classic integer sequence tightly linked to the Stern–Brocot tree of positive rationals. The resulting list begins zero, one, one, two, one, three, two, three, one, four, three, five, two, five, three, four, and continues with the striking property that consecutive terms are always coprime.
What Stern's diatomic sequence is and how the even/odd recurrence works
Begin with the seeds s of zero equals zero and s of one equals one. For every later index the rule depends only on parity. If n is even, write n equals two k and set s of n equal to s of k—the same value appears at half the index.
If n is odd, write n equals two k plus one and set s of n equal to s of k plus s of k plus one. Unrolling a few steps produces zero, one, one, two, one, three, two, three, one, four, three, five, two, five, three, four, one, five, four, seven, three, and so on.
Adjacent pairs are always coprime, every positive rational appears exactly once as a consecutive ratio s of m over s of m plus one when you walk the sequence, and that enumeration is exactly the Stern–Brocot tree flattened by breadth. The same recurrence is sometimes called the Calkin–Wilf or Stern–Brocot sequence depending on presentation; this tool uses the standard diatomic form with s of zero equal to zero.
Because every step is exact integer addition or a pure index halving, there is no rounding error and no dependence on wall-clock time or random seeds.
What you can do with it
Programming contest and interview prep validators
Assert candidate solutions for Stern sequence or Stern–Brocot tree problems without reimplementing the recurrence in every language harness.
Teaching demos of coprime consecutive pairs and rational enumeration
Project n, stern, formula, and recurrence in class so learners see the seeds, the even and odd rules, and how consecutive ratios cover the positive rationals.
FAQ
What is Stern's diatomic sequence?
The sequence defined by s(0)=0, s(1)=1, s(2k)=s(k), and s(2k+1)=s(k)+s(k+1). It begins 0, 1, 1, 2, 1, 3, 2, 3, 1, 4, 3, 5, … and is linked to the Stern–Brocot tree.
Why is it called Stern–Brocot?
Walking consecutive pairs s(n)/s(n+1) enumerates every positive rational exactly once—the same structure as the Stern–Brocot tree of fractions. The sequence itself is Stern's diatomic sequence.
What is s(0) and s(1)?
Under the convention used here, s(0)=0 and s(1)=1. Every later term follows from the even and odd index rules. The response always echoes the recurrence so the seeds are explicit.
Is the Stern–Brocot sequence calculator free?
The browser tool is free and runs locally.
How do I work out s(10) by hand?
Halve the index while it is even and split it when it is odd. Since 10 is even, s(10) equals s(5); 5 is odd, so s(5) equals s(2) plus s(3), which is 1 plus 2, giving 3.
Related tools
For developers — API access
Everything on this page is available programmatically. This section is for teams who want to wire it into their own systems; everyone else can just use the tool above.
API endpoint
Prefer to automate it? One authenticated POST creates the task; the result comes back by webhook or a signed link. The same capability also runs here on the web, by email and from Telegram — and soon from our app too.
Call it from your stack
curl -X POST https://api.kit.forhosting.com/math/stern-brocot \
-H "Authorization: Bearer $KIT_KEY" \
-H "Content-Type: application/json" \
-d '{"n":10}'const res = await fetch("https://api.kit.forhosting.com/math/stern-brocot", {
method: "POST",
headers: {
"Authorization": `Bearer ${process.env.KIT_KEY}`,
"Content-Type": "application/json"
},
body: JSON.stringify({
"n": 10
})
});
const { task_id } = await res.json();import os, requests
res = requests.post(
"https://api.kit.forhosting.com/math/stern-brocot",
headers={"Authorization": f"Bearer {os.environ['KIT_KEY']}"},
json={
"n": 10
},
)
task_id = res.json()["task_id"]<?php
$res = file_get_contents("https://api.kit.forhosting.com/math/stern-brocot", false, stream_context_create([
"http" => [
"method" => "POST",
"header" => "Authorization: Bearer " . getenv("KIT_KEY") . "\r\nContent-Type: application/json",
"content" => '{"n":10}',
],
]));
$task = json_decode($res, true);body := bytes.NewBufferString(`{"n":10}`)
req, _ := http.NewRequest("POST", "https://api.kit.forhosting.com/math/stern-brocot", body)
req.Header.Set("Authorization", "Bearer "+os.Getenv("KIT_KEY"))
req.Header.Set("Content-Type", "application/json")
res, _ := http.DefaultClient.Do(req)Example request
{
"n": 10
}Example response
{
"task_id": "tsk_a1b2c3d4e5f6a1b2c3d4e5f6",
"type": "math.stern_brocot",
"status": "queued",
"_links": {
"result": "/tasks/tsk_…/result"
}
}The API is asynchronous: the call returns a task_id immediately and the result arrives by webhook. Polling is capped at 1 req/s per task.
Pricing
Published price — no tokens, no invented credits. A failed task is never charged.
Limits
max_n | 1000000000 |
Errors
| HTTP | Code | Meaning |
|---|---|---|
401 | unauthorized | Missing or invalid API key. |
402 | insufficient_balance | Your balance doesn't cover the task price. |
404 | unknown_type | That task type doesn't exist. |
429 | rate_limited | Too many requests. Use the webhook instead of polling. |
Technical notes
It is defined by two seed values and a split rule on the parity of the index: s of zero is zero, s of one is one; when the index is even and equal to two k the term equals s of k; when the index is odd and equal to two k plus one the term equals s of k plus s of k plus one.
What Stern's diatomic sequence is and how the even/odd recurrence works
When you only need a single term, send the index n; the response echoes n, the Stern value, a short formula string for the even and odd cases, and the full recurrence seed description so graders and students can recompute by hand or on paper.
How to call the API and what comes back
A successful response includes n as echoed, stern equal to s of n, formula equal to the compact even and odd rules, and recurrence documenting the seeds together with s of two k equals s of k and s of two k plus one equals s of k plus s of k plus one. Use it from homework pipelines, programming-contest validators, interview-prep sandboxes, notebook enrichment jobs, or any workflow that needs a reproducible Stern term without installing specialized sequence packages on every machine. For multiprecision indices beyond that limit, use a dedicated big-integer stack instead of this lightweight parse capability. Send a JSON body with a single required field n: a non-negative whole number at most one billion, the index of the Stern term you want. Aliases index and order are accepted for the same meaning. Failed validation—a missing n, a non-integer, a fraction, a value above the published limit of one billion, or any negative number—returns invalid_input and is never charged. Pricing is a flat $0.002 per successful request with unit item and zero marginal unit price. Keep n inside the published cap; the even/odd walk is logarithmic in n, so a single request stays cheap on the Worker and in the browser.
Practical tips, limits, and related searches
When grading, assert both the stern field and the formula string so a wrong recurrence or a Fibonacci mix-up is easy to diagnose. Sibling landings in this kit cover other sequence and figurate intents such as Padovan numbers, triangular numbers, polygonal numbers, and arithmetic series sums; this page is specifically for people searching for a Stern–Brocot sequence calculator, Stern diatomic numbers, or the n-th term of Stern's sequence. Do not treat the integer alone as a black box—pair it with the documented even and odd rules when teaching so alternate OEIS offsets are not confused with the s of zero equals zero convention used here. Prefer paired classroom examples: n equals zero yields zero; n equals one yields one; n equals ten yields three; n equals fifteen yields four; and a negative n demonstrates the hard rejection path with invalid_input. Because consecutive terms are always coprime, students can check gcd of s of n and s of n plus one by hand for small n and match the API. Failed tasks that return invalid_input do not consume prepaid balance, which keeps exploratory scripts cheap when users type bad values while learning the contract. Cap n at one billion so every request stays bounded; if you need larger indices, switch to big-integer tooling outside this free parse path.
Integration use cases
Homework: compute the n-th Stern diatomic term
Give students an index and check their hand-computed Stern value against a deterministic API or free browser result with the same even/odd recurrence and seeds.
Technical questions
What inputs are rejected?
Missing n, non-integers, values above 1_000_000_000, and any negative number return invalid_input. Those failures are not charged.