Co-prime Check

beginner Math and Number Theory

Problem

Two numbers are co-prime when their gcd is 1. Read a and b and print true if they are co-prime, else false.

Constraints

  • 0 <= a, b <= 10^9

Examples

Input

8 15

Output

true

Solutions

Best approachTime O(log min)Space O(1)

Two numbers share no common factor other than 1 exactly when their gcd is 1.

Same code works in Java810172125Basic features only, so nothing changes between versions.
/*
 * Problem : Check if two numbers are co-prime.
 * Input   : Two integers.
 * Output  : true or false.
 * Approach: Co-prime means gcd = 1.
 * Time    : O(log min)
 * Space   : O(1)
 * Java    : 8 or newer.
 */
import java.util.Scanner;

public class Main {
    // This method solves the task. It receives the input and returns the answer.
    static boolean solve(long a, long b) {
        // Step 1: Find the gcd with Euclid's algorithm.
        long x = a;
        long y = b;
        while (y != 0) {
            long remainder = x % y;
            x = y;
            y = remainder;
        }

        // Step 2: The numbers are co-prime when the gcd is 1.
        return x == 1;
    }

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        long a = scanner.nextLong();
        long b = scanner.nextLong();
        System.out.println(solve(a, b));
    }
}
Hints (1)
  1. What is gcd(0, 5)?