按题要求:随机取2个不同数,一共有7*6/2=21种取法。其中互质的情况有:
(2,3),(2,5),(2,7)
(3,4),(3,5),(3,7),(3,8)
(4,5),(4,7)
(5,6),(5,7),(5,8)
(6,7),
(7,8)
一共14种。
所以这个2个数互质的概率为 14 / 24 = 2/3。
写个python 验证一下。
import random
def isCoprime(x,y):
if x == 1 and y == 1:
return True
elif x <= 0 or y <=0 or x==y:
return False
elif x==1 or y ==1:
return True
else:
tmp = 0
while(True):
tmp = x%y
if tmp == 0:
break
else:
x = y
y = tmp
if y == 1:
return True
else:
return False
total = 0
coPrimeCount = 0
for i in range(100000):
x = random.randint(2,8)
y = random.randint(2,8)
if(x == y):
continue
if isCoprime(x,y):
coPrimeCount = coPrimeCount + 1
total = total + 1
print(coPrimeCount / total)