KnowledgeBoat Logo

Computer Applications

Write a 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.

Java

Java Iterative Stmts

205 Likes

Answer

import java.util.Scanner;

public class KboatCoprime
{
    public void checkCoprime() {
        
        Scanner in = new Scanner(System.in);
        System.out.print("Enter a: ");
        int a = in.nextInt();
        System.out.print("Enter b: ");
        int b = in.nextInt();
        
        int hcf = 1;
        
        for (int i = 1; i <= a && i <= b; i++) {
            if (a % i == 0 && b % i == 0)
                hcf = i;
        }
        
        if (hcf == 1)
            System.out.println(a + " and " + b + " are co-prime");
        else
            System.out.println(a + " and " + b + " are not co-prime");
    }
}

Variable Description Table

Program Explanation

Output

BlueJ output of Write a 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.

Answered By

71 Likes


Related Questions