Java 检查一个数是否为互质数
如果两个数的最大公约数为1,则称这两个数为互质数。
为了更加清楚,任何一个数都可能有多个约数,在某些情况下,两个数的约数之间可能有一些公共约数。因此,如果在任何情况下,两个数的最大公约数为1,那么这两个数就被称为互质数。简单来说,这意味着这两个数除了1之外没有其他公共因数。换句话说,我们可以说这两个数是互质数。
一些互质数的示例为 – (2, 3),(3, 7),(11, 19) … 等。
为了演示一些实例 –
实例1
Input numbers are 2 and 3.
Let’s check it by using the logic of the Coprime number.
Divisors of 2 are 1 and 2.
Divisors of 3 are 1 and 3.
As you notice the maximum common divisor available here is 1.
Here 2 and 3 are coprime numbers.
实例2
Input numbers are 8 and 15.
Let’s check it by using the logic of the Coprime number.
Divisors of 8 are 1, 2, 4 and 8.
Divisors of 15 are 1, 3, 5 and 15.
As you notice the maximum common divisor available here is 1.
Here 8 and 15 are coprime numbers.
实例3
Input numbers are 9 and 18.
Let’s check it by using the logic of the Coprime number.
Divisors of 9 are 1, 3, and 9.
Divisors of 18 are 1, 2, 3, 6, 9 and 18.
As you notice the maximum common divisor available here is 9.
Here 9 and 18 are not coprime numbers.
步骤
步骤-1 - 通过静态输入方法获取输入数字。
步骤-2 - 找出所有数字的除数并返回最大公约数。
步骤-3 - 然后检查最大公约数是否为1。
步骤-4 - 若条件为真,则打印两个数字是互质数,否则不是。
多种方法
我们提供了不同的解决方法。
- 通过用户定义的方法使用静态输入值。
- 通过用户定义的方法使用用户输入值。
让我们逐个查看程序及其输出。
方法1:使用用户定义的方法和静态输入值
在这种方法中,我们声明两个变量并初始化它们的值。然后通过将这些数字作为参数传递给一个用户定义的方法来调用该方法,并在方法内部找出两个数字的所有除数并返回最大公约数。然后通过传递这个最大公约数调用另一个方法,并检查它是否等于1。如果等于1,则按照逻辑输入的数字是互质数,否则不是。
示例
public class Main{
public static void main (String[] args) {
int firstNumber = 5, secondNumber = 6;
checkCoprime(firstNumber, secondNumber);
}
static void checkCoprime(int F, int S) {
if ( commonDivisor(F, S) == 1)
System.out.println("(" + F + " & " + S + ") are Co-Prime numbers");
else
System.out.println("(" + F + " & " + S + ") are not Co-Prime numbers");
}
static int commonDivisor(int F, int S) {
if (F == 0 || S == 0)
return 0;
if (F == S)
return F;
if (F > S)
return commonDivisor(F-S, S);
return commonDivisor(F, S-F);
}
}
输出
(5 & 6) are Co-Prime numbers
方法2:使用用户输入的值。
在这种方法中,我们声明两个变量并获取用户输入的值。然后通过将这些数字作为参数来调用一个用户定义的方法,并在方法内部找出两个数字的所有约数并返回最大公约数。然后通过将这个最大公约数作为参数调用另一个方法,并检查它是否为1。如果是1,则根据逻辑输入的数字是互质数,否则不是。
示例
import java.util.*;
public class Main{
public static void main (String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print(" Enter First number: ");
int firstNumber = sc.nextInt();
System.out.print(" Enter second number: ");
int secondNumber = sc.nextInt();
checkCoprime(firstNumber, secondNumber);
}
static void checkCoprime(int F, int S) {
if ( commonDivisor(F, S) == 1)
System.out.println("(" + F + " & " + S + ") are Co-Prime numbers");
else
System.out.println("(" + F + " & " + S + ") are not Coprime numbers");
}
static int commonDivisor(int F, int S) {
if (F == 0 || S == 0)
return 0;
if (F == S)
return F;
if (F > S)
return commonDivisor(F-S, S);
return commonDivisor(F, S-F);
}
}
输出
Enter First number: 5
Enter second number: 6
(5 & 6) are Co-Prime numbers
在本文中,我们探讨了如何使用不同的方法在Java中检查两个数字是否是互质数。