[英]How can I randomly generate a number with a condition that is shares NO common factors with two other randomly generated numbers
p1 = 1097
p2 = 1279
p = p1*p2
phi = (p1-1)*(p1-1)
我想隨機生成一個數字>phi,它在“p”和“phi”之間不共享公因數
從已知素數構造數字以使它們不共享相同的素數(作為因子)應該比創建隨機數、分解它們並檢查它們的非重疊因子更快。
算法:
可以這樣做:
# get or calculate some primes that are big enough
# starting with
primes = [1097,1103,1109,1117,1123,1129,1151,
1153,1163,1171,1181,1187,1193,1201,1213,1217,1223,1229,1231,
1237,1249,1259,1277,1279,1283,1289,1291,1297,1301,1303,1307,
1319,1321,1327,1361,1367,1373,1381,1399,1409,1423,1427,1429,
1433,1439,1447,1451,1453,1459,1471,1481,1483,1487,1489,1493,
1499,1511,1523,1531,1543,1549,1553,1559,1567,1571,1579,1583,
1597,1601,1607,1609,1613,1619,1621,1627,1637,1657,1663,1667,
1669,1693,1697,1699,1709,1721,1723,1733,1741,1747,1753,1759,
1777,1783,1787,1789,1801,1811,1823,1831,1847,1861,1867,1871,
1873,1877,1879,1889,1901,1907,1913,1931,1933,1949,1951,1973,
1979,1987,1993,1997,1999,2003,2011,2017,2027,2029,2039,2053,
2063,2069,2081,2083,2087,2089,2099,2111,2113,2129,2131,2137,
2141,2143,2153,2161,2179,2203,2207,2213,2221,2237,2239,2243,
2251,2267,2269,2273,2281,2287]
然后在其中選擇索引並將它們相乘以獲得結果:
import random
from operator import mul
from functools import reduce
random.seed(42)
choices = random.choices
def m(numbers):
return reduce(mul, numbers, 1)
# how many numbers to use to factorize the number you want
size = 5
# draw f.e. 5 factors from then
p1 = [primes[i] for i in choices(range(len(primes)), k=size)]
# draw 5 others that are not in p1
p2 = []
while len(p2) != size:
p2 = [primes[i] for i in choices(range(len(primes)), k=3 * size) if i not in p1][:size]
# calculate them
print( m(p1), m(p2)) # 8058608274530453 8642866553052643
您選擇的要使用的素數應該大於您想要用來乘以結果的數字的兩倍,否則您可能會陷入長時間運行的循環中。 提供大約 5 到 10 倍的要用作因子的素數應該足夠了。
不確定“不要在 p 和 phi 之間共享公因數”是什么意思,因為 p 和 phi 不會有公因數
One of the "bruteforce" ways to do it would be to run a Poisson random variable to get an integer n, then to compute the decomposition of each integer bigger than psi until you get the n-th integer bigger than psi satisfying your condition.
我會看到的另一種方法是采用大於 psi 的隨機 integer (例如泊松隨機變量)並檢查它們是否滿足您的條件。
取決於你的意思和你的數字的大小。
編輯:我建議泊松變量,因為它們允許您避免為隨機數設置任意硬編碼上限
您可以使用 python 中的random
模塊生成隨機數。
要發現p
和phi
沒有公因數,您可以使用p*phi
檢查最大公約數 (GCD)。
from math import gcd as calcGcd
from random import randint
def getRandom(lower, upper, *noFacWithThese):
for _ in range(upper - lower): # to avoid infinite loop
randNum = randint(lower, upper)
if noCommonFactors(randNum, noFacWithThese):
return randNum
return None
def noCommonFactors(base, withThese):
withThis = 1
for n in withThese: # find mutiplication of numbers inside 'withThese' list
withThis *= n
return calcGcd(base, withThis) == 1
p1 = 1097
p2 = 1279
p = p1*p2
phi = (p1-1)*(p1-1)
while True:
print( getRandom(1, 10000, p, phi) )
input()
確保為randint
function 使用必要的下限和上限。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.