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 中檢查兩個數字是否為互質數。
廣告