4. Write a java program to enter two numbers and check whether they are co-prime or not
[Two numbers are said to be co-prime, if their HCF is 1 (one).]
Sample Input: 14, 15
Sample Output: They are co-prime.
Answers
Follows are the program to check co-prime number:
import java.util.*;//import package
public class Main//defining class
{
public static void main(String[] abc)//main method
{
int n1,n2,t,mr=-1;//defining integer variable
Scanner obxc=new Scanner(System.in);//creating Scanner classs object for input values
System.out.print("Enter first number: \n");//print message
n1=obxc.nextInt();//input first value
System.out.print("Enter second number: \n");//print message
n2=obxc.nextInt();//input second value
if(n2>n1)//use if to check n2 value is greater then n1
{//swap the value
t=n2;//hold n2 value in t
n2=n1;//holding n1 value in n2
n1=t;//holding t value in n1
}
while(mr!=0)//defining while loop to check HCF value
{
mr=n1%n2;//holding remainder value
n1=n2;//holding n2 value in to n1
n2=mr;//holding remainder value in n2 variable
}
if(n1==1)//use if to check n1 value is equal to 1
{
System.out.println("CO-prime");//print message CO-prime
}
else //else block
{
System.out.println("not CO-prime");//print message not CO-prime
}
}
}
Output:
Enter first number:
14
Enter second number:
15
CO-prime
Explanation:
Inside the main method, four integer variable "n1,n2,t, and mr" is defined, in which "n1, n2" is used for input value and if block to check grater then value and swap it.
After swapping the while loop is defined that uses the "mr" variable to hold the remainder value of n1 and n2 and after calculating, this value if block is used to check n1 is equal to 1 and print the message of co-prime or goto else block that prints not co-prime.