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

  1. #!/usr/bin/python
  2. import time
  3. import random
  4. import os
  5. def demultiply(product, factor_a_min, factor_a_max, factor_b_min, factor_b_max):
  6.     # Naive solution, brute force.
  7.     
  8.                                                 ## x = a * b
  9.                                                 ## x in P, P in Z
  10.                                                 ## a in Z
  11.                                                 ## b in Z
  12.     
  13.     possibilities = []                          ## P
  14.     
  15.     # Loop over all possible values of a.
  16.     factor_a = factor_a_min                     ## a
  17.     while factor_a <= factor_a_max:
  18.         
  19.         if factor_a:
  20.         
  21.             factor_b = product//factor_a        ## b
  22.             # Verify that both a and b are integers.
  23.             if factor_a * factor_b == product:
  24.                 
  25.                 if factor_b_min <= factor_b <= factor_b_max:
  26.                     possibilities.append((factor_a, factor_b))
  27.         
  28.         factor_a += 1
  29.     
  30.     return possibilities
  31. class tester():
  32.     def __init__(self, factor_a_range, factor_b_range, samples):
  33.         self.factor_a_min, self.factor_a_max = factor_a_range
  34.         self.factor_b_min, self.factor_b_max = factor_b_range
  35.         self.samples = samples
  36.         self.times = []
  37.         self.n_solutions = {}
  38.     
  39.     def one(self):
  40.         a = random.randint(self.factor_a_min, self.factor_a_max)
  41.         b = random.randint(self.factor_b_min, self.factor_b_max)
  42.         
  43.         T0 = time.time()
  44.         P = demultiply(
  45.             a * b,
  46.             self.factor_a_min, self.factor_a_max,
  47.             self.factor_b_min, self.factor_b_max
  48.         )
  49.         T1 = time.time()
  50.         
  51.         self.times.append(T1-T0)
  52.         
  53.         if len(P) in self.n_solutions:
  54.             self.n_solutions[len(P)] += 1
  55.         else:
  56.             self.n_solutions[len(P)] = 1
  57.     
  58.     def test(self):
  59.         self.times = []
  60.         self.n_solutions = {}
  61.         
  62.         for i in range(self.samples):
  63.             self.one()
  64.         
  65.         
  66. def web():
  67.     pass
  68.     
  69. if __name__ == '__main__':
  70.     
  71.     if os.getenv('QUERY_STRING'):
  72.         web()
  73.     
  74.     t = tester((22000000, 23000000), (63000000, 64000000), 1000)
  75.