Advertisement
pyzuki

pickle_attempt_for_web3.py

Aug 12th, 2012
64
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 5.17 KB | None | 0 0
  1. # pickle_attempt_for_web3.py
  2.  
  3. from time import time as t
  4. import pickle
  5. import gmpy2
  6. import random
  7. import os.path
  8.  
  9. def int_digits_num(n):
  10.     """
  11.    Given an integer, (positive, 0, or negative), or an expression that
  12.    evaluates to an integer, returns the number of digits in the integer.
  13.    """
  14.     from math import log10
  15.     if not isinstance(n, int):
  16.         raise TypeError("WTF you didn't pass me an int")
  17.     if n == 0:
  18.         return 1
  19.     n = abs(n)
  20.     return int(log10(n)) + 1
  21.  
  22. def int_commas(n):
  23.     """
  24.    inserts commas into integers and returns the string
  25.  
  26.    E.g. -12345678 -> -12,345,789
  27.    """
  28.     return format(n, ',d')
  29.  
  30. def printTime(timeStart, timeEnd):
  31.     from mycalc import hmsToText
  32.     timeElapsed = timeEnd - timeStart
  33.     if timeElapsed > 60:
  34.         print("Time was", hmsToText(timeElapsed))
  35.     else:
  36.         print("Time was %.4g seconds" % timeElapsed)
  37.  
  38. def randIntOfGivenLength(length):
  39.     """
  40.    Return a random int of a given number of digits
  41.    """
  42.     return random.randint(10**(length-1), 10**length - 1)
  43.  
  44. def findFactor(n, startingAt):
  45.     """
  46.    Written by Kent Johnson
  47.    """
  48.     limit = int(n**.5) + 1
  49.     x = startingAt
  50.     while x < limit:
  51.         if not n % x:
  52.             return x
  53.         x += 2
  54.     return False
  55.  
  56. def factorsOfInteger(n):
  57.     """
  58.    Return list of prime factors of n.
  59.    Returns [n] if n is prime.
  60.    Re-written largely by Kent Johnson
  61.    """
  62.     factors = []
  63.     if n == 1:
  64.         return [1]
  65.     # Get the factors of two out of the way to simplify findFactor
  66.     while n % 2 == 0:
  67.         factors.append(2)
  68.         n = n // 2
  69.     lastFactor = 3
  70.     r = n
  71.     while True:
  72.         factor = findFactor(r, lastFactor)
  73.         if not factor:
  74.             # r is prime
  75.             if r == 1: # This is needed, at least for powers of 2
  76.                 break
  77.             factors.append(r)
  78.             break
  79.         factors.append(factor)
  80.         lastFactor = factor
  81.         r = r // factor # correcting an error in previous versions
  82.     if len(factors) == 1:
  83.         return factors
  84.     factors[-1] = int(factors[-1]) # without this some last factors are floats, ending in .0
  85.     return factors
  86.  
  87. D = {}
  88. if os.path.getsize('factors.txt') == 2:
  89.     #The file exists, but is empty; leave it alone
  90.     pass
  91.  
  92. elif os.path.exists('factors.txt'):
  93.     #The file exists and is not empty: use it
  94.     f = open("factors.txt", 'rb')
  95.     data = pickle.load(f)
  96.     f.close
  97.     D = data
  98.    
  99. else:
  100.     # create the file and close it
  101.     f = open("factors.txt", 'wb')
  102.     f.close
  103.    
  104. print("D has", int_commas(len(D)), "entries")
  105. begin = 1000100000
  106. w = 900000
  107. end = begin + w
  108.  
  109. add_flag = 0
  110. if add_flag == 1:
  111.     t0 = t()
  112.     for n in range(begin, end):
  113.         factors_list = factorsOfInteger(n)
  114.         D[n] = factors_list
  115.    
  116.     t1 = t()
  117.     printTime(t0,t1)
  118.     print()
  119.     print("D now has", int_commas(len(D)), "entries")
  120.  
  121. print()
  122.  
  123. while True:
  124.     oldnew_flag = 0
  125.     print("Enter a positive integer OR")
  126.     print("Enter nothing to generate an 18-digit integer OR")
  127.     print("Enter a zero to close the program.")
  128.     print()
  129.     s = input("> ")
  130.    
  131.     if "10**" in s:
  132.         n = 10**(int(s[4:]))
  133.         plus = input("plus: ")
  134.         if plus == '':
  135.             plus = 0
  136.         else:
  137.             plus = int(plus)
  138.         n += plus
  139.        
  140.     elif s != '':
  141.         n = int(s)
  142.        
  143.         if n >= 10**19:
  144.             print(n, "is too big: calculation might take too long.")
  145.             print("Choose another n")
  146.             print()
  147.             continue
  148.        
  149.         elif gmpy2.is_prime(n) and len(str(n)) >= 18:
  150.             print(n, "is prime -- will take too long.")
  151.             print("Choose another n")
  152.             print()
  153.             continue  
  154.        
  155.     elif s == '':
  156.         n = randIntOfGivenLength(18)
  157.         print("n =", n, "a random 18-digit integer")
  158.         n, r = find_large_prime_factors_of_large_ints(n)
  159.        
  160.         if gmpy2.is_prime(n):
  161.             print(n, "is prime -- will take too long.")
  162.             print("Choose another n")
  163.             print()
  164.             continue
  165.        
  166.         elif r == 1:
  167.             print(n, "has a large prime factor -- will take too long.")
  168.             print("Choose another n")
  169.             print()
  170.             continue
  171.        
  172.     if n == 0:
  173.         print("D has", int_commas(len(D)), "entries")
  174.         f = open("factors.txt", 'wb')
  175.         pickle.dump(D, f)
  176.         f.close
  177.         break
  178.    
  179.     t0 = t()
  180.    
  181.     try:
  182.         factors = D[n]
  183.         print("the factors of", int_commas(n), "are", factors)
  184.         oldnew_flag = 1
  185.         print("OLD")
  186.        
  187.     except KeyError:
  188.         factors = factorsOfInteger(n)
  189.         print("the factors of", int_commas(n), "are", factors)
  190.         D[n] = factors
  191.         oldnew_flag = 2
  192.         print("NEW")
  193.        
  194.     t1 = t()
  195.    
  196.     print()
  197.    
  198.     #print(D.items())
  199.     #print(D.values())
  200.     #print(D.keys())
  201.     printTime(t0,t1)
  202.     if oldnew_flag == 1:
  203.         print("OLD ENTRY")
  204.     elif oldnew_flag == 2:
  205.         print("NEW ENTRY")
  206.     print("D has", int_commas(len(D)), "entries")
  207.     print()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement