Co-Primes in Java
In this tutorial, we will learn to distinguish co-primes from non-co-primes and implement it in Java.
So what exactly are Co-Primes?
Co-Primes
When two numbers have no common factor except “1” then such a pair of numbers are called as Co-primes.
Hence in simple words, if the HCF of the two numbers is 1, then they are called as Co-primes.
Co-primes are also called as Relatively Prime or Mutually Prime.
Note: These two numbers may or may not be prime
Explanation of Co-Primes or not with example
Example 1:
Let number1: 5
Let number2: 50
Factors of number1 are: 1, 5
Factors of number2 are: 1, 2, 5, 10, 25, 50
HCF is 5
Hence they are Not Co-Primes.
Example 2:
Let number1: 14
Let number2: 15
Factors of number1 are: 1, 2, 7, 14
Factors of number2 are: 1, 3, 5, 15
HCF is 1
Hence they are Co-Primes.
Code for Finding Co-Primes or not in Java
import java.util.*; class coprimes { public static void main(String[]args) { Scanner scan = new Scanner(System.in); System.out.print("Enter number 1: "); int num1 = scan.nextInt(); ArrayList<Integer> arr1 = new ArrayList<Integer>(); System.out.print("Enter number 2: "); int num2 = scan.nextInt(); ArrayList<Integer> arr2 = new ArrayList<Integer>(); for(int i = 0, j = 2; i < num1 ; i++, j++) { if(num1 % j == 0) // for finding factors { arr1.add(j); //storing the factors in a list } } for(int i = 0, j = 2; i < num2; i++, j++) { if(num2 % j == 0) { arr2.add(j); } } if(num2 > num1) { arr2.retainAll(arr1); //retains all the common elements in both the lists in arr2 boolean isEqual = arr1.equals(arr2); if(isEqual) { System.out.println("Not Co-Primes"); } else { System.out.println("Co-Primes"); } } else { arr1.retainAll(arr2); //retains all the common elements in both the lists in arr1 boolean isEqual = arr1.equals(arr2); if(isEqual) { System.out.println("Not Co-Primes"); } else { System.out.println("Co-Primes"); } } } }
Output:
Enter number 1: 2 Enter number 2: 3 Co-Primes
Hope you’ve understood the code 🙂
Any questions feel free to drop in your comments
You can also check other posts:
Leave a Reply