In the previous article, we have discussed Java Program to Check Circular Prime Number
In this article we are going to understand what Coprime number is and how we can check whether a number is Coprime or not in Java with examples.
Java Program to Check Coprime Number
Coprime numbers are two integers a
and b
which are said to be relatively prime, mutually prime, or coprime if the only positive integer that divides both of them is 1.
Example: 13, 15-> Coprime number 67, 60 -> Coprime number 99, 33 -> Not a Coprime number
In the above examples the number 19 is only a Coprime number.
Let’s see different ways to check co prime numbers.
Our website provided core java programs examples with output aid beginners and expert coders to test their knowledge gap and learn accordingly.
Approach:
- We ask the user to enter a number which we store in an integer variable
num
. - We set
GCD =1
and then check for any other greatest common divisor of the number. - If flag is true, it is said to be a Coprime number or else it is not.
Method-1: Java Program to Check Coprime Number By Using Static Value
import java.util.Scanner; public class CoPrimeNumber{ public static void main(String args[]) { //Two prime numers are declared int num1 = 13; int num2 = 17; //GCD is the greates coomon divisor of both numbers int min , max, gcd = 1; // Assigning min and max values if(num1<num2) { min = num1; max = num2; } else { min = num2; max = num1; } while (max > min) { int remainder = max % min; if (remainder == 0) { gcd = min; break; } else { max = min; min = remainder; } } if (gcd == 1) { System.out.println(num1+" and "+num2+" are Co Prime Numbers"); } else { System.out.println(num1+" and "+num2+" are Not Co Prime Numbers"); } } }
Output: 13 and 17 are Co Prime Numbers
Method-2: Java Program to Check Coprime Number By Using User Input Value
import java.util.Scanner; public class CoPrimeNumber{ public static void main(String args[]) { //Taking the number as input from the user using scanner class Scanner scan = new Scanner(System.in); System.out.print("Enter first number : "); int num1 = scan.nextInt(); System.out.print("Enter second number : "); int num2 = scan.nextInt(); //GCD is the greates coomon divisor of both numbers int min , max, gcd = 1; // Assigning min and max values if(num1<num2) { min = num1; max = num2; } else { min = num2; max = num1; } while (max > min) { int remainder = max % min; if (remainder == 0) { gcd = min; break; } else { max = min; min = remainder; } } if (gcd == 1) { System.out.println(num1+" and "+num2+" are Co Prime Numbers"); } else { System.out.println(num1+" and "+num2+" are Not Co Prime Numbers"); } } }
Output: Enter first number : 3 Enter second number : 5 3 and 5 are Co Prime Numbers
Don’t miss the chance of Java programs examples with output pdf free download as it is very essential for all beginners to experienced programmers for cracking the interviews.
Related Java Programs: