Two numbers are coprime (or relatively prime) if they have no common factors other than 1. In other words, their greatest common divisor (GCD) is 1. In this blog post, we will see how to write a simple Python program to determine if two given numbers are coprime.
For example:
- 8 and 15 are coprime because their only common divisor is 1.
- 9 and 12 are not coprime because they share a common divisor of 3.
Python Code to Check Coprime Numbers
Python provides a built-in math
module that includes a gcd
function, which makes it easy to determine if two numbers are coprime. Here’s a simple Python function to check if two numbers are coprime using the math.gcd()
function:
import math
import argparse
def are_coprime(a, b):
return math.gcd(a, b) == 1
def main():
"""
This program finds if two number are coprime
"""
# provide two numbers from command line
parser = argparse.ArgumentParser(description="Check coprime")
parser.add_argument("-n1", type=int, required=True, help="provide a positive number")
parser.add_argument("-n2", type=int, required=True, help="provide another positive number")
args = parser.parse_args()
# check the numbers provide by user
if args.n1 <= 0 or args.n2 <= 0:
print("Both numbers should be positive")
else:
if are_coprime(args.n1, args.n2):
print(f"{args.n1} and {args.n2} are coprime.")
else:
print(f"{args.n1} and {args.n2} are not coprime.")
if __name__ == "__main__":
main()
To run this code, save it as coprime_checker.py (or any preferred name you like) and execute it from the command line with two positive numbers, as shown below:
python coprime_checker.py -n1 8 -n2 15
Please let me know in the comments if you encounter any issues with the code.