Generating Random Factored Numbers, Easily
April 17, 2018
Sometimes it is convenient to have large random composite numbers with known factorization, particularly for testing prime number programs. Eric Bach gives a fast but complicated method. Adam Kalai gives a simpler method that’s not so fast:
Input: Integer n > 0.
Output: A uniformly random number 1 ≤ r ≤ n.
- Generate a seqneuce n ≥ s1 ≥ s2 ≥ … ≥ si = 1 by choosing s1 ∈ {1, 2, …, n} and si+1 ∈ {1, 2, … si}, until reaching 1.
- Let r be the product of the prime si‘s.
- If r ≤ n, output r with probability r / n.
- Otherwise, RESTART.
Your task is to implement Kalai’s method of generating random composite numbers with their factorization. When you are finished, you are welcome to read or run a suggested solution, or to post your own solution or discuss the exercise in the comments below.
In Python.
from random import randrange
from ma.primee import is_prime
def kalai(n):
while True:
s, r = n, 1
while s > 1:
s = randrange(1, s)
if is_prime(s):
r *= s
if r <= n and randrange(1, n+1) <= r:
return r
Oops, forgot to format.
A later and more correct version is on ideone.
Here’s a solution in C++11 using GMP. Prime checking is probabilistic and can return false positives with some non-zero probability (and consequently a factorization that can include composites).
Example:
[…] Read More […]