给定两个数字,任务是使用命令行参数找到两个数字的 HCF。两个数的 GCD(最大公约数)或 HCF(最高公约数)是将它们相除的最大数。
例子:
Input: n1 = 10, n2 = 20
Output: 10
Input: n1 = 100, n2 = 101
Output: 1
方法:
- 由于数字是作为命令行参数输入的,因此不需要专用的输入行
- 从命令行参数中提取输入数字
- 提取的数字将是字符串类型。
- 将这些数字转换为整数类型并将其存储在变量中,比如 num1 和 num2
- 找出数字的 HCF。一个有效的解决方案是使用欧几里得算法,这是用于此目的的主要算法。这个想法是,如果从较大的数字中减去较小的数字,则两个数字的 GCD 不会改变。
- 打印或返回 HCF
程序:
C
// C program to compute the HCF of two numbers
// using command line arguments
#include
#include /* atoi */
// Function to compute the HCF of two numbers
int HCF(int a, int b)
{
if (b == 0)
return a;
return HCF(b, a % b);
}
// Driver code
int main(int argc, char* argv[])
{
int num1, num2;
// Check if the length of args array is 1
if (argc == 1)
printf("No command line arguments found.\n");
else {
// Get the command line argument and
// Convert it from string type to integer type
// using function "atoi( argument)"
num1 = atoi(argv[1]);
num2 = atoi(argv[2]);
// Find the HCF and print it
printf("%d\n", HCF(num1, num2));
}
return 0;
}
Java
// Java program to compute the HCF of two numbers
// using command line arguments
class GFG {
// Function to compute the HCF of two numbers
static int HCF(int a, int b)
{
if (b == 0)
return a;
return HCF(b, a % b);
}
// Driver code
public static void main(String[] args)
{
// Check if length of args array is
// greater than 0
if (args.length > 0) {
// Get the command line argument and
// Convert it from string type to integer type
int num1 = Integer.parseInt(args[0]);
int num2 = Integer.parseInt(args[1]);
// Find the HCF
int res = HCF(num1, num2);
// Print the HCF
System.out.println(res);
}
else
System.out.println("No command line "
+ "arguments found.");
}
}
输出:
- 在 C 中:
- 在Java:
想要从精选的视频和练习题中学习,请查看C++ 基础课程,从基础到高级 C++ 和C++ STL 课程,了解语言和 STL。要完成从学习语言到 DS Algo 等的准备工作,请参阅完整的面试准备课程。