📅  最后修改于: 2023-12-03 15:27:59.675000             🧑  作者: Mango
给定一个整数数组,数组元素均为正整数,求出其中数字乘积为复合数的所有数组元素。
对于一个正整数,若其因子中存在大于1且小于它本身的整数,则它为复合数。因此,可以对数组中的每个正整数进行因子分解,并判断其因子中是否存在不为1且小于它本身的整数,若存在则说明该数字为复合数。
代码如下所示:
def is_composite(num):
if num < 2:
return False
for i in range(2, int(num ** 0.5) + 1):
if num % i == 0:
return True
return False
def get_factors(num):
factors = []
for i in range(2, num):
if num % i == 0:
factors.append(i)
return factors
def get_composite_numbers(nums):
result = []
for num in nums:
factors = get_factors(num)
for factor in factors:
if is_composite(factor):
result.append(num)
break
return result
nums = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 12, 14, 15, 16, 18, 20, 21, 22, 24, 25]
print(get_composite_numbers(nums)) # [4, 6, 8, 9, 10, 12, 14, 15, 16, 18, 20, 21, 22, 24]
以上就是本文的介绍。