Browse Source

Lucas number algorithm

Petra Lamborn 5 years ago
parent
commit
3609182312
1 changed files with 37 additions and 1 deletions
  1. 37
    1
      lucas.py

+ 37
- 1
lucas.py View File

@@ -79,8 +79,44 @@ def Jacobi(a, n):
79 79
         return -1 * Jacobi(n, a)
80 80
     return Jacobi(n, a)
81 81
 
82
+def FirstD(n):
83
+    """Return first D in the sequence 5, -7, 9, -11, 13, -15... for which the
84
+    Jacobi symbol (D/n) is -1
85
+    """
86
+    if hasIntSQRT(n):
87
+        raise ValueError("n must not be a square")
88
+    if n < 1 or n % 2 == 0:
89
+        raise ValueError("n must be a positive odd number")
90
+    for D in Dsequence():
91
+        if Jacobi(D/n) == -1:
92
+            return D
93
+    # Shouldn't fire
94
+    return 0
95
+
96
+def Lucas(n, p, q):
97
+    """Function for generating values of a lucas sequence with parameters p, q.
98
+    Via formula at <https://en.wikipedia.org/wiki/Lucas_sequence>
99
+    """
100
+    if n < 0:
101
+        raise ValueError("n must be a non-negative integer")
102
+    if n == 0:
103
+        return 0, 2
104
+    Unm1, Vnm1 = Lucas(n - 1, p, q)
105
+    Un = (p * Unm1 + Vnm1) // 2
106
+    Vn = ((p * p - 4 * q) * Unm1 + p * Vnm1) // 2
107
+    return Un, Vn
108
+
109
+def LucasUn(n, p, q):
110
+    """Return only the U numbers from a lucas sequence Un(P, Q). For example if
111
+    P = 1, and Q = -1 this will return the Fibonacci numbers; if P = 3 and Q =
112
+    2 then it returns the Mersenne numbers etc.
113
+    """
114
+    return Lucas(n, p, q)[0]
82 115
 
83
-
116
+def LucasVn(n, p, q):
117
+    """Return only V numbers from a local sequence Vn(P, Q).
118
+    """
119
+    return Lucas(n, p, q)[1]
84 120
 
85 121
 
86 122