What's a computationally sane way to, given a natural number n
, generate a random number that is relatively prime to n
?
对于一个自然数n,什么是计算上合理的方法,生成一个相对于n的素数?
I'm willing to sacrifice some randomness and coverage of all possibilities for speed. That is, if I only ever hit perhaps 75% of the possible (smaller) relative primes, that's fine.
我愿意牺牲一些随机性和对速度的所有可能性的报道。也就是说,如果我只命中可能的(较小的)相对质数的75%,那也可以。
3 个解决方案
#1
2
in simple words:
用简单的话说:
unsigned random_prime(unsigned n){
unsigned r = rand(), t;
while ((t = gcd(r, n)) > 1)
r /= t;
return r;
}
#2
10
"I'm willing to sacrifice randomness and coverage of all possibilities for speed." Given n, select n+1.
“我愿意牺牲随机性和覆盖速度的所有可能性。”给定的n,n + 1选择。
You're going to need to be more specific.
你需要更具体一些。
#3
5
The probability that two random integers are relatively prime to one another works out to 6/pi^2 (in the limit, for large N), or approximately 61%. So generate-and-test should be a viable strategy -- the GCD calculation is about O(log n), and you will probably get a result in 2 or 3 trials.
两个随机整数的概率相对彼此'工作6 /π^ 2(在极限情况下,大型N),或大约61%。所以生成和测试应该是一种可行的策略——GCD的计算大约是O(log n),你可能会在两三次试验中得到结果。
#1
2
in simple words:
用简单的话说:
unsigned random_prime(unsigned n){
unsigned r = rand(), t;
while ((t = gcd(r, n)) > 1)
r /= t;
return r;
}
#2
10
"I'm willing to sacrifice randomness and coverage of all possibilities for speed." Given n, select n+1.
“我愿意牺牲随机性和覆盖速度的所有可能性。”给定的n,n + 1选择。
You're going to need to be more specific.
你需要更具体一些。
#3
5
The probability that two random integers are relatively prime to one another works out to 6/pi^2 (in the limit, for large N), or approximately 61%. So generate-and-test should be a viable strategy -- the GCD calculation is about O(log n), and you will probably get a result in 2 or 3 trials.
两个随机整数的概率相对彼此'工作6 /π^ 2(在极限情况下,大型N),或大约61%。所以生成和测试应该是一种可行的策略——GCD的计算大约是O(log n),你可能会在两三次试验中得到结果。