【每日一题20220614】互为质数

:mage:‍ 给定两个位于2到99之间到数字,如果它们公因子只有数字1,则称它们互为质数。请编写一个函数,判断给定的两个数字是否互为质数,如果是返回True,否则返回False。

【示例】
输入:20, 27
输出:True
解释:20的因子有1, 2, 4, 5, 10, 20;27的因子有1, 3, 9, 27。所以公因子是1,互为质数。

题目难度:简单
题目来源:codewars-Coprime Validator

def solution(n1: int, n2: int) -> bool:
    # your code here

assert solution(20, 27) is True
assert solution(12, 39) is False
assert solution(15, 98) is True
assert solution(18, 98) is False
def solution(n1: int, n2: int) -> bool:
    # your code here
    lis1 = [i for i in range(1, n1 + 1) if n1 % i == 0]
    lis2 = [i for i in range(1, n2 + 1) if n2 % i == 0]
    return True if set(lis1).intersection(lis2) == {1} else False


assert solution(20, 27) is True
assert solution(12, 39) is False

1 Like
def solution(n1: int, n2: int) -> bool:
    # your code here
    max_num = max(n1, n2)
    index_num = 2
    while index_num <= max_num:
        if n1 % index_num == 0 and n2 % index_num == 0:
            return False
        index_num += 1
    return True

assert solution(20, 27) is True
assert solution(12, 39) is False
assert solution(15, 98) is True
assert solution(18, 98) is False
def solution(n1: int, n2: int) -> bool:
    if n1 > n2:
        n1, n2 = n2, n1
    for i in range(2, n1 + 1):
        if n1 % i == 0 and n2 % i == 0:
            return False
    return True
def solution(n1: int, n2: int):
    flag = True
    for i in range(2, n1 + 1):
        if n1 % i == 0:
            if n2 % i == 0:
                flag = False
                break
    return flag

def solution(n1: int, n2: int) -> bool:
    def factor_list(num: int) -> set:
        s = set()
        for i in range(1, int(num ** 0.5) + 1):
            if num % i == 0:
                j = num / i
                s.update([i, j])
        return s

    new_set = factor_list(n1) & factor_list(n2)
    if len(new_set) > 1:
        return False
    return True


assert solution(20, 27) is True
assert solution(12, 39) is False
assert solution(15, 98) is True
assert solution(18, 98) is False
def solution(n1:int,n2:int) -> bool:
    while (n1%n2)!=0:
        r = n1%n2
        n1 = n2
        n2 = r
    return True if n2==1 else False

assert solution(20, 27) is True
assert solution(12, 39) is False
assert solution(15, 98) is True
assert solution(18, 98) is False
def solution(n1: int, n2: int)-> bool:
    rest1 = [i for i in range(1, n1) if n1 % i == 0]
    rest2 = [i for i in range(1, n2) if n2 % i == 0]

    if (set(rest1) & set(rest2) ) != {1}:
        return False

    return True

assert solution(20, 27) is True
assert solution(12, 39) is False
assert solution(15, 98) is True
assert solution(18, 98) is False
关闭