source code of /small-scripts/demultiply.py
Last modified | |
Lines | 80 |
Parent directory Download CGIread sitemap Main page
Quick links: __init__ demultiply one test tester web
#!/usr/bin/python
import time
import random
import os
def demultiply(product, factor_a_min, factor_a_max, factor_b_min, factor_b_max):
# Naive solution, brute force.
## x = a * b
## x in P, P in Z
## a in Z
## b in Z
possibilities = [] ## P
# Loop over all possible values of a.
factor_a = factor_a_min ## a
while factor_a <= factor_a_max:
if factor_a:
factor_b = product//factor_a ## b
# Verify that both a and b are integers.
if factor_a * factor_b == product:
if factor_b_min <= factor_b <= factor_b_max:
possibilities.append((factor_a, factor_b))
factor_a += 1
return possibilities
class tester():
def __init__(self, factor_a_range, factor_b_range, samples):
self.factor_a_min, self.factor_a_max = factor_a_range
self.factor_b_min, self.factor_b_max = factor_b_range
self.samples = samples
self.times = []
self.n_solutions = {}
def one(self):
a = random.randint(self.factor_a_min, self.factor_a_max)
b = random.randint(self.factor_b_min, self.factor_b_max)
T0 = time.time()
P = demultiply(
a * b,
self.factor_a_min, self.factor_a_max,
self.factor_b_min, self.factor_b_max
)
T1 = time.time()
self.times.append(T1-T0)
if len(P) in self.n_solutions:
self.n_solutions[len(P)] += 1
else:
self.n_solutions[len(P)] = 1
def test(self):
self.times = []
self.n_solutions = {}
for i in range(self.samples):
self.one()
def web():
pass
if __name__ == '__main__':
if os.getenv('QUERY_STRING'):
web()
t = tester((22000000, 23000000), (63000000, 64000000), 1000)