Solution (source code)

= Solution

For a regular <Lagrangian>, define the <canonical momentum> $p_i=\partial L/\partial\dot q_i$ and invert this relation for $\dot q(q,p,t)$. Its <Legendre transform> is the <Hamiltonian>
$$
H(q,p,t)=p\mathbin\cdot\dot q-L(q,\dot q,t).
$$
Since $L\,dt=p\cdot dq-H\,dt$, the <action> is
$$
S=\int_{t_1}^{t_2}(p\cdot\dot q-H)\,dt
=\int(p\cdot dq-H\,dt).
$$
For independent variations with $\delta q(t_1)=\delta q(t_2)=0$,
$$
\delta S=\int_{t_1}^{t_2}
\left[(\dot q-\partial_pH)\cdot\delta p
-(\dot p+\partial_qH)\cdot\delta q\right]dt.
$$
Stationarity for arbitrary $\delta p$ and $\delta q$ gives <Hamilton's equations> $\dot q=\partial_pH$ and $\dot p=-\partial_qH$.