Saturday, October 25, 2025
HomeLanguagesPython | Count the array elements with factors less than or equal...

Python | Count the array elements with factors less than or equal to the factors of given x

Given an array, the task is to count the elements of array whose factors are less than the given number x. Examples:

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.

Approach: Find out factors of all the elements and that of given xand after that compare all of them if factors of elements are less than that of factors of x, then increment the count. Below is the implementation of above problem – 

Python3




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<count_fac:
            ans+=1
  
    return ans
  
  
# Driver code
  
arr = [2,12,4,6]
x = 6
print(Totalcount(arr, x))


Output:

2

Time Complexity: O(?x+n?k) where n is the size of the array, x is the given number, and k is the maximum element in the array.
Auxiliary Space: O(n)

Dominic
Dominichttp://wardslaus.com
infosec,malicious & dos attacks generator, boot rom exploit philanthropist , wild hacker , game developer,
RELATED ARTICLES

Most Popular

Dominic
32361 POSTS0 COMMENTS
Milvus
88 POSTS0 COMMENTS
Nango Kala
6728 POSTS0 COMMENTS
Nicole Veronica
11892 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11954 POSTS0 COMMENTS
Shaida Kate Naidoo
6852 POSTS0 COMMENTS
Ted Musemwa
7113 POSTS0 COMMENTS
Thapelo Manthata
6805 POSTS0 COMMENTS
Umr Jansen
6801 POSTS0 COMMENTS