Python: Check if two given numbers are Co Prime or not
Co-Prime Checker
Two numbers are coprime if their highest common factor (or greatest common divisor if you must) is 1.
Write a Python program to check if two given numbers are Co Prime or not. Return True if two numbers are Co Prime otherwise return false.
Sample Solution:
Python Code:
# Define a function 'gcd' to calculate the greatest common divisor (GCD) of two positive integers.
def gcd(p, q):
# Use Euclid's algorithm to find the GCD.
while q != 0:
p, q = q, p % q
return p
# Define a function 'is_coprime' to check if two numbers are coprime (GCD is 1).
def is_coprime(x, y):
# Check if the GCD of 'x' and 'y' is equal to 1.
return gcd(x, y) == 1
# Test cases to check if pairs of numbers are coprime.
print(is_coprime(17, 13))
print(is_coprime(17, 21))
print(is_coprime(15, 21))
print(is_coprime(25, 45))
Sample Output:
True True False False
Explanation:
Here is a breakdown of the above Python code:
- GCD calculation (gcd function):
- The "gcd()" function uses Euclid's algorithm to calculate the greatest common divisor of two positive integers ('p' and 'q').
- Coprime check (is_coprime function):
- The "is_coprime()" function checks if two numbers ('x' and 'y') are coprime by comparing their GCD with 1.
- Test cases:
- The script includes test cases to check whether pairs of numbers are coprime using the 'is_coprime' function.
Flowchart:
Python Code Editor:
Have another way to solve this solution? Contribute your code (and comments) through Disqus.
Previous: Write a Python program to show the individual process IDs (parent process, process id etc.) involved.
Next: Write a Python program to calculate Euclid's totient function of a given integer. Use a primitive method to calculate Euclid's totient function.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics