给定一个数组arr[]和一个整数K ,任务是计算数组中存在的K因子的计数。
例子:
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}
朴素的方法:这个问题的一个简单解决方案是找到 K 的所有因子,然后对每个因子迭代数组并检查它是否存在于数组中。如果是,则将因子计数增加 1。
有效的方法:这个想法不是找到数字 K 的所有因子,而是在数组上迭代并检查每个元素是否是 K 的因子,或者不是在模运算符的帮助下。如果是,则增加 K 的因子计数。
下面是上述方法的实现:
C++
// C++ implementation to find the count
// of factors of K present in array
#include
using namespace std;
// Function to find the count
// of factors of K present in array
int calcCount(int arr[], int n, int k)
{
int count = 0;
// Loop to consider every
// element of array
for (int i = 0; i < n; i++) {
if (k % arr[i] == 0)
count++;
}
return count;
}
// Driver Code
int main()
{
int arr[] = { 1, 2, 4, 5, 6 };
int n = sizeof(arr) / sizeof(arr[0]);
int k = 6;
// Function Call
cout << calcCount(arr, n, k);
return 0;
}
Java
// Java implementation to find the count
// of factors of K present in array
class GFG{
// Function to find the count
// of factors of K present in array
static int calcCount(int arr[], int n, int k)
{
int count = 0;
// Loop to consider every
// element of array
for(int i = 0; i < n; i++)
{
if (k % arr[i] == 0)
count++;
}
return count;
}
// Driver Code
public static void main(String[] args)
{
int arr[] = { 1, 2, 4, 5, 6 };
int n = arr.length;
int k = 6;
// Function Call
System.out.print(calcCount(arr, n, k));
}
}
// This code is contributed by gauravrajput1
Python3
# Python3 implementation to find the count
# of factors of K present in array
# Function to find the count
# of factors of K present in array
def calcCount(arr, n, k):
count = 0
# Loop to consider every
# element of array
for i in range(0, n):
if (k % arr[i] == 0):
count = count + 1
return count
# Driver Code
arr = [ 1, 2, 4, 5, 6 ]
n = len(arr)
k = 6
# Function Call
print(calcCount(arr, n, k))
# This code is contributed by PratikBasu
C#
// C# implementation to find the count
// of factors of K present in array
using System;
class GFG{
// Function to find the count
// of factors of K present in array
static int calcCount(int []arr, int n, int k)
{
int count = 0;
// Loop to consider every
// element of array
for(int i = 0; i < n; i++)
{
if (k % arr[i] == 0)
count++;
}
return count;
}
// Driver Code
public static void Main(String[] args)
{
int []arr = { 1, 2, 4, 5, 6 };
int n = arr.Length;
int k = 6;
// Function Call
Console.Write(calcCount(arr, n, k));
}
}
// This code is contributed by Amit Katiyar
Javascript
输出:
3
时间复杂度: O(N)
如果您想与行业专家一起参加直播课程,请参阅Geeks Classes Live