-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathtrial_division.py
48 lines (46 loc) · 1.35 KB
/
trial_division.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
# -*- coding: utf-8 -*-
from factorization_function import *
from benchmark import *
# Trial Division - https://en.wikipedia.org/wiki/Trial_division
class TrialDivision(FactorizationFunction):
@classmethod
def getCharacteristics(self):
c = FactorizationFunctionCharacteristics()
c.canFactorizePrimeComposites = True
c.canFactorizeEvenComposites = True
return c
@classmethod
def factorize(self, n, returnBenchmark=False, modified=False):
# Setup
benchmark = Benchmark()
factors = [1]
# Start of algorithm
benchmark.start()
if modified:
while n % 2 == 0:
benchmark.iterate()
factors.append(2)
n /= 2
f = 3
while n > 1:
benchmark.iterate()
if n % f == 0:
factors.append(f)
n /= f
else:
f += 2
else:
f = 2
while n > 1:
benchmark.iterate()
if (n % f == 0):
factors.append(f)
n /= f
else:
f += 1
# End of algorithm
benchmark.stop()
if returnBenchmark:
return (factors, benchmark)
else:
return factors