Python|计算因子小于或等于给定 x 因子的数组元素
给定一个数组,任务是计算数组中因子小于给定数x的元素。
例子:
Input: arr = [2, 12, 4, 6], x = 6
Output: 2
factors of x = 6 is [1, 2, 3]
factors of arr[0] = 2 is [1]
factors of arr[1] = 12 is [1, 2, 3, 4]
factors of arr[2] = 4 is [1, 2]
factors of arr[3] = 6 is [1, 2, 3]
so only arr[0] and arr[2] are the answer.
方法:
找出所有元素的因数和给定x的因数,然后比较它们,如果元素的因数小于x的因数,则增加计数。
下面是上述问题的实现——
from math import ceil, sqrt
# function to count the factors of an array
def factorscount(x):
count = 0
for i in range(1,ceil(sqrt(x))):
if x%i==i:
count+=1
else:
count+=2
return count
def Totalcount(arr, x):
# count of factors of given x
count_fac = factorscount(x)
# store the count of each factors
arr_fac = [factorscount(i) for i in arr]
ans = 0
for i in arr_fac:
# if factors count of element of array is
#small than that of given number
if i
输出:
2