给定三个数字x,y和k,找出x和y的第k个公因子。如果x和y的公因数少于k,则打印-1。
例子 :
Input : x = 20, y = 24
k = 3
Output : 4
Common factors are 1, 2, 4, ...
Input : x = 4, y = 24
k = 2
Output : 2
Input : x = 22, y = 2
k = 3
Output : -1
我们发现两个数字中较小的一个是因为公因子不能大于较小的数字。然后,我们运行从1到较小数字的循环。对于每个数字i,我们检查它是否是一个公因数。如果是,我们将增加公因子的计数。
下面是实现:
C++
// C++ program to find kth common factor
// of two numbers
#include
using namespace std;
// Returns k'th common factor of x and y.
int findKCF(int x, int y, int k)
{
// Find smaller of two numbers
int small = min(x, y);
// Count common factors until we either
// reach small or count becomes k.
int count = 1;
for (int i=2; i<=small; i++)
{
if (x % i==0 && y % i == 0)
count++;
if (count == k)
return i;
}
// If we reached small
return -1;
}
// Driver code
int main()
{
int x = 4, y = 24, k = 3;
cout << findKHCF(x, y, k);
return 0;
}
Java
// Java program to find kth
// common factor of two numbers
import java.lang.*;
class GFG {
// Returns k'th common factor of x and y.
static int findKHCF(int x, int y, int k) {
// Find smaller of two numbers
int small = Math.min(x, y);
// Count common factors until we either
// reach small or count becomes k.
int count = 1;
for (int i = 2; i <= small; i++) {
if (x % i == 0 && y % i == 0)
count++;
if (count == k)
return i;
}
// If we reached small
return -1;
}
// Driver code
public static void main(String[] args) {
int x = 4, y = 24, k = 3;
System.out.print(findKHCF(x, y, k));
}
}
// This code is contributed by Anant Agarwal.
Python3
# Python program to find
# kth common factor
# of two numbers
# Returns k'th common
# factor of x and y.
def findKHCF(x,y,k):
# Find smaller of two numbers
small = min(x, y)
# Count common factors
# until we either
# reach small or count
# becomes k.
count = 1
for i in range(2,small+1):
if (x % i==0 and y % i == 0):
count=count + 1
if (count == k):
return i
# If we reached small
return -1
# Driver code
x = 4
y = 24
k = 3
print(findKHCF(x, y, k))
# This code is contributed
# by Anant Agarwal.
C#
// C# program to find kth
// common factor of two numbers
using System;
class GFG {
// Returns k'th common factor of x and y.
static int findKHCF(int x, int y, int k)
{
// Find smaller of two numbers
int small = Math.Min(x, y);
// Count common factors until we either
// reach small or count becomes k.
int count = 1;
for (int i = 2; i <= small; i++)
{
if (x % i == 0 && y % i == 0)
count++;
if (count == k)
return i;
}
// If we reached small
return -1;
}
// Driver code
public static void Main()
{
int x = 4, y = 24, k = 3;
Console.Write(findKHCF(x, y, k));
}
}
// This code is contributed by Nitin Mittal.
PHP
Javascript
输出 :
4