Count the factors of K present in the given Array
Last Updated :
16 Aug, 2022
Given an array arr[] and an integer K, the task is to calculate the count the factors of K present in the array.
Examples:
Input: arr[] = {1, 2, 4, 5, 6}, K = 6
Output: 3
Explanation:
There are three numbers present in the array those are factors of K = 6 – {1, 2, 6}
Input: arr[] = {1, 2, 12, 24}, K = 20
Output: 2
Explanation:
There are two numbers present in the array those are factors of K = 20 – {1, 2}
Naive Approach: A simple solution for this problem is to find all the factors of K and then for each factor iterate over the array and check that it is present in the array or not. If yes then increment the count of factors by 1.
Efficient Approach: The idea is to instead of finding all factors of the number K iterate over the array and check for each element that it is the factor of K, or not with the help of the modulo operator. If yes then increment the count of factors of K.
Below is the implementation of the above approach:
C++
#include <iostream>
using namespace std;
int calcCount( int arr[], int n, int k)
{
int count = 0;
for ( int i = 0; i < n; i++) {
if (k % arr[i] == 0)
count++;
}
return count;
}
int main()
{
int arr[] = { 1, 2, 4, 5, 6 };
int n = sizeof (arr) / sizeof (arr[0]);
int k = 6;
cout << calcCount(arr, n, k);
return 0;
}
|
Java
class GFG{
static int calcCount( int arr[], int n, int k)
{
int count = 0 ;
for ( int i = 0 ; i < n; i++)
{
if (k % arr[i] == 0 )
count++;
}
return count;
}
public static void main(String[] args)
{
int arr[] = { 1 , 2 , 4 , 5 , 6 };
int n = arr.length;
int k = 6 ;
System.out.print(calcCount(arr, n, k));
}
}
|
Python3
def calcCount(arr, n, k):
count = 0
for i in range ( 0 , n):
if (k % arr[i] = = 0 ):
count = count + 1
return count
arr = [ 1 , 2 , 4 , 5 , 6 ]
n = len (arr)
k = 6
print (calcCount(arr, n, k))
|
C#
using System;
class GFG{
static int calcCount( int []arr, int n, int k)
{
int count = 0;
for ( int i = 0; i < n; i++)
{
if (k % arr[i] == 0)
count++;
}
return count;
}
public static void Main(String[] args)
{
int []arr = { 1, 2, 4, 5, 6 };
int n = arr.Length;
int k = 6;
Console.Write(calcCount(arr, n, k));
}
}
|
Javascript
<script>
function calcCount(arr, n, k)
{
var count = 0;
for ( var i = 0; i < n; i++) {
if (k % arr[i] == 0)
count++;
}
return count;
}
var arr = [ 1, 2, 4, 5, 6 ];
var n = arr.length;
var k = 6;
document.write( calcCount(arr, n, k));
</script>
|
Time Complexity: O(N)
Auxiliary Space: O(1), since no extra space has been taken.
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...