-
Notifications
You must be signed in to change notification settings - Fork 2
/
ruffini.py
70 lines (56 loc) · 1.46 KB
/
ruffini.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
#!/usr/bin/env python
#
# Author Dario Clavijo 2015
# GPLv3
from math import *
# tells if a n is prime or not
def isPrime(n):
return all(n % i != 0 for i in range(2, int(n**0.5) + 1))
# finds the prime factors of n
def factors(n):
factor = []
limit = int(round(sqrt(n), 2)) + 1
check = 2
num = n
if isPrime(n):
return [n]
for check in range(2, limit):
if isPrime(check) and (num % check) == 0:
factor.append(check)
num /= check
if isPrime(num):
factor.append(num)
break
return sorted(factor)
# add the negative factors to try
def addnegatives(D):
nD = []
for i in D:
nD.extend((-abs(i), abs(i)))
return nD
# one step ruffini
def ruffini_step(P, D):
for i in range(len(D)):
tmpPoli = []
for j in range(len(P)):
if j == 0:
tmpPoli.append(P[j])
else:
tmpPoli.append(P[j] + (D[i] * tmpPoli[j - 1]))
if tmpPoli[-1] == 0:
return [D[i], tmpPoli]
def ruffini_test(P):
print(("P=", P))
TI = P[len(P) - 1]
D = [1] + factors(abs(TI)) + [abs(TI)]
D = addnegatives(D)
D.sort()
print(("D=", D))
tmp = P
for k in range(len(P) - 3):
ret = ruffini_step(tmp, D)
tmp = ret[1]
print(("Grade=", len(P) - k, "root=", ret[0], "coefs=", ret[1]))
# P = [1,-7,13,23,-78]
P = [6, -29, 27, 27, -29, 6]
ruffini_test(P)