![]() |
We are going to learn how we can Check if the given two numbers are coprime or not using JavaScript. Co-prime are two integers that have no common factors other than 1. Their greatest common divisor (GCD) is 1. Coprime numbers are also known as relatively prime numbers. Example:Input: a = 15 and b = 4 These are the following methods: Table of Content Iterative MethodCreate the function. Use a for loop to iterate from 2 up to the minimum of a and b. This loop checks all possible divisors starting from 2. Check if both a and b are divisible by the current iteration number i. If they are, it means i is a common factor of a and b, so return false i.e. they are not coprime. If loop finishes without finding any common factors the return true. Example: To demonstrate checking if two numbers are coprime or not using iterative method.
Output Are 21 and 28 coprime? false Time Complexity: O(min(a, b)) Space Complexity: O(1) Euclidean AlgorithmIn this approach, we are using Euclidean Algorithm. Create a function GCD and pass a and b as input parameter. Check if b is equal to 0 then return a. else recursively call GCD with b and the remainder of a divided by b. Create another function to check co-prime and pass a and b as input parameter. Call the gcd function with a and b. Return true if the result of gcd(a, b) is 1, indicating that a and b are coprime. Else return false. Example: To demonstrate checking if two numbers are coprime or not using Euclidean Algorithm.
Output 3 and 7 are coprime. Time Complexity: O(min(a, b)) Space Complexity: O(1) Using Prime FactorizationIn this approach, we find the prime factors of both numbers and check if they have any common prime factors other than 1. If they don’t, the numbers are coprime. Example: This JavaScript code demonstrates how to check if two numbers are coprime using prime factorization.
Output Are 15 and 4 coprime? true Are 28 and 14 coprime? false |
Reffered: https://www.geeksforgeeks.org
JavaScript |
Type: | Geek |
Category: | Coding |
Sub Category: | Tutorial |
Uploaded by: | Admin |
Views: | 13 |