📅  最后修改于: 2023-12-03 15:40:17.163000             🧑  作者: Mango
本文介绍了一种算法,用于找到给定序列中最长的,由相邻元素相乘得到的素数序列。
def is_prime(n):
if n < 2:
return False
for i in range(2, int(n ** 0.5) + 1):
if n % i == 0:
return False
return True
def longest_primes_subsequence(nums):
dp = [1] * len(nums)
for i in range(1, len(nums)):
for j in range(i):
if is_prime(nums[j]) and nums[i] % nums[j] == 0:
dp[i] = max(dp[i], dp[j] + 1)
return max(dp)
# example
nums = [2, 3, 6, 7, 8, 21, 23]
longest_primes_subsequence(nums) # 3