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 中检查两个数字是否为互质数。
广告
数据结构
网络
关系数据库管理系统(RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP