In this tutorial you will learn about the Program to check CoPrime Numbers Program in Java and its application with practical example.
In this tutorial, we will learn to create a Java Program to check CoPrime Numbers Program in Java
Prerequisites
Before starting with this tutorial, we assume that you are best aware of the following Java programming concepts:
- Java Operators.
- Basic Input and Output function in Java.
- Class and Object in Java.
- Basic Java programming.
- If-else statements in Java.
- For loop in Java.
What is Co-prime Number.
The numbers are said to be co-prime, if their GCD is “1”
So 13,14 and 15 are co-prime numbers.
Program to check CoPrime Numbers Program in Java
In this program we would find the given two number are co-prime or not first will take the input from the user and check they arr coprime or not. let have a look at the code
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 |
//java program to find co -prime import java.io.*; import java.util.*; class Co_prime { public static void main(String args[]) { //declaring variables and taking vlaues from user.. Scanner in= new Scanner(System.in); int num1,num2,a,i,c=0; System.out.println("Enter two Numbers"); num1= in.nextInt(); num2= in.nextInt(); a=num1*num2; // condition for co-prime number for(i=1;i<num1;i++) { if(num1%i==0 && num2%i==0) { c=i; } } // if result is 1 they are co-prime number if(c==1) { System.out.println("Numbers are Co prime : "+num1+" & "+num2); } else { System.out.println("Numbers are not Co prime : "+num1+" & "+num2); } }// end of main method }// end of class |
Output
Co-prime
Not a Co-prime
In the above program, we have first declared and initialized a set variables required in the program.
- Num1,num2 = it will hold entered numbers
- a= for iteration.
- c= for count.
After declaring variables we take two values from user.
Co-prime numbers are the numbers whose common factor is 1 lets look at the example.
1 2 3 4 5 6 7 |
Number 2 3 The factors of 2 are 1, 2. and factor of 3 is 1,3 They are Co-Prime. Input : 4 8 The factors of 4 are 1, 2 and 4. and factor of 8 is 1,2,4 and 8 They are not Co-Prime. |
after that we find factors of given number
if number has common factor 1 then they are co-prime
if not they are not co-prime numbers.