On Fri, Jul 04, 2014 at 09:24:31AM -0400, Kynn Jones wrote: > I'm looking for a way to implement pseudorandom primary keys in the range > 100000..999999. > > The randomization scheme does not need to be cryptographically strong. As > long as it is not easy to figure out in a few minutes it's good enough. Well, a trick that produces a not too easy to guess sequence is: X(n) = p^n mod q where q is prime. Pick the largest prime that will fit, in this case 899981 (I beleive) and some random p, say 2345. Then 100000 + (2345^n) mod 899981 should be a sequence fitting your purpose. Unfortunatly, the pow() function in Postgres can't be used here (too slow and it overflows), but python has a helpful function: In [113]: len( set( pow(2345, n, 899981) for n in range(899981) ) ) Out[113]: 899980 You could probably write an equivalent function in Postgres if necessary. Hope this helps, -- Martijn van Oosterhout <kleptog@xxxxxxxxx> http://svana.org/kleptog/ > He who writes carelessly confesses thereby at the very outset that he does > not attach much importance to his own thoughts. -- Arthur Schopenhauer
Attachment:
signature.asc
Description: Digital signature