Pick a random number between 0 and n using a constant source of randomness Task 

Given a positive integer n less than 2^30 specified as input in any way you choose, your code should output a random integer between 0 and n, inclusive.  The number you generate should be chosen uniformly at random. That is each value from 0 to n must occur with equal probability (see Rules and Caveats).

Rules and Caveats

Your code can assume that any random number generator built into your language or standard library that claims to be uniformly random is in fact uniform. That is you don't have to worry about the quality of the random source you are using. However,


You do have to establish that if the random source you are using is uniform then your code correctly outputs a uniform random integer from 0 to n.
Any arguments when calling a built in or library random function must be constant. That is they must be completely independent of the input value.
Your code may terminate with probability 1 rather than being guaranteed to terminate.


Notes


randInt(0,n) is not valid as it takes the input as an argument to a builtin or library function.
rand()%n will not give a uniform random number in general.  As an example given by betseg, if intmax == 15 and n = 10, then you will be much more likely to get 0-5 than 6-10. 
floor(randomfloat()*(n+1)) will also not give a uniform random number in general due to the finite number of different possible floating point values between 0 and 1.
x86 machines with rdrand instruction, 10 bytes

BITS 64

_try_again:

 rdrand eax
jnc _try_again

 cmp eax, edi
ja _try_again

 ret


machine code

0FC7F0 73FB 39F8 77F7 C3




The input is in the register rdi and the output in rax.
This respects the SYS V AMD64 ABI so the code effectively implement a C function 

unsigned int foo(unsigned int max); 


with 32-bit ints.

The instruction rdrand is described by Intel


  RDRAND returns random numbers that are supplied by a cryptographically secure, deterministic random bit generator DRBG. The DRBG is designed to meet the NIST SP 800-90A standard.


Dealing with CSRNG it is implicit that the distribution is uniform, anyway, quoting the NIST SP 800-90A:


  A random number is an instance of an unbiased random variable,
  that is, the output produced by a uniformly distributed random process.




The procedure generates a random number and if it is non-strictly greater than the input it is returned.
Otherwise, the process is reiterated.  

Since eax is 32-bit, rdrand returns a number between 0 and 232-1, so for every n in [0, 232-1] the number of expected iterations is 232/(n+1) which is defined for all n in [0, 230).