소스 검색

Added some utility functions for rule matches.

Taddeus Kroes 14 년 전
부모
커밋
9f8b2e9cb0
1개의 변경된 파일41개의 추가작업 그리고 0개의 파일을 삭제
  1. 41 0
      src/rules/utils.py

+ 41 - 0
src/rules/utils.py

@@ -8,3 +8,44 @@ def nary_node(operator, scope):
     """
     return scope[0] if len(scope) == 1 \
            else Node(operator, nary_node(operator, scope[:-1]), scope[-1])
+
+
+def is_prime(n):
+    """
+    Check if the given integer n is a prime number.
+    """
+    if n == 2:
+        return True
+
+    if n < 2 or not n & 1:
+        return False
+
+    for i in xrange(3, int(n ** .5) + 1, 2):
+        if not divmod(n, i)[1]:
+            return False
+
+    return True
+
+
+def gcd(a, b):
+    """
+    Return greatest common divisor using Euclid's Algorithm.
+    """
+    while b:
+        a, b = b, a % b
+
+    return a
+
+
+def lcm(a, b):
+    """
+    Return least common multiple of a and b.
+    """
+    return a * b // gcd(a, b)
+
+
+def least_common_multiple(*args):
+    """
+    Return lcm of args.
+    """
+    return reduce(lcm, args)