Просмотр исходного кода

Added some utility functions for rule matches.

Taddeus Kroes 14 лет назад
Родитель
Сommit
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)