📅  最后修改于: 2023-12-03 15:40:34.302000             🧑  作者: Mango
在编程中,我们经常要处理数字,其中包括如何检查数组中所有可被K整除的复合数字的GCD是否为斐波那契数。本篇文章将介绍如何进行这项任务。
def gcd(a, b):
if b == 0:
return a
else:
return gcd(b, a % b)
def prime_factors(n):
i = 2
factors = {}
while i * i <= n:
if n % i:
i += 1
else:
n //= i
if i not in factors:
factors[i] = 1
else:
factors[i] += 1
if n > 1:
if n not in factors:
factors[n] = 1
else:
factors[n] += 1
return factors
def check_fibonacci_gcd(arr, k):
fib = [1, 1]
while fib[-1] < max(arr):
fib.append(fib[-1] + fib[-2])
divisible_numbers = [i for i in arr if i % k == 0]
if len(divisible_numbers) < 2:
return False
gcd_num = divisible_numbers[0]
for num in divisible_numbers[1:]:
gcd_num = gcd(gcd_num, num)
if gcd_num <= 2:
return False
factors = prime_factors(gcd_num)
for num in fib:
if num in factors and factors[num] > 0:
factors[num] -= 1
if num in factors and factors[num] == 0:
factors.pop(num)
if len(factors) == 0:
return True
else:
return False
def test_check_fibonacci_gcd():
assert check_fibonacci_gcd([2, 4, 6], 2) == True
assert check_fibonacci_gcd([2, 4], 2) == False
assert check_fibonacci_gcd([2], 2) == False
assert check_fibonacci_gcd([2, 3, 5], 2) == False
assert check_fibonacci_gcd([2, 3, 5, 8], 2) == True
assert check_fibonacci_gcd([2, 4, 6], 4) == False
assert check_fibonacci_gcd([], 2) == False
assert check_fibonacci_gcd([1, 1], 1) == False
assert check_fibonacci_gcd([3, 3, 3], 3) == False
test_check_fibonacci_gcd()
以上就是一个简单实用的检查数组中所有可被K整除的复合数字的GCD是否为斐波那契数的程序。