Given an integer n >= 1
as input, output a sample from the discrete triangular distribution over the integers k
, for 1 <= k <= n
(1 <= k < n
is also acceptable),
defined by p(k) ∝ k
.
E.g. if n = 3
, then p(1) = 1/6
, p(2) = 2/6
, and p(3) = 3/6
.
Your code should take constant expected time, but you are allowed to ignore overflow, to treat floating point operations as exact, and to use a PRNG (pseudorandom number generator).
You can treat your random number generator and all standard operations as constant time.
This is code golf, so the shortest answer wins.
n
inrandom_function(n)
, or whether this matters. \$\endgroup\$