Guest User

Primefactors revisited

a guest
May 17th, 2018
38
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.51 KB | None | 0 0
  1. from typing import List, Any
  2.  
  3.  
  4. def binarysearch(n: int, l: list, low, high):
  5.     if high < low:    return low
  6.     mid = int(low + ((high - low) / 2))
  7.  
  8.     if (n == l[mid]):   return mid
  9.     if mid == low: return high
  10.     if mid == high: return low
  11.     elif n > l[mid]:
  12.         return binarysearch(n, l, mid, high)
  13.     else:
  14.         return binarysearch(n, l, low, mid - 1)
  15.  
  16.  
  17.  
  18. class primes:
  19.  
  20.     def __init__(self) :
  21.         self.primescache = [2]
  22.         self.lastnumber = 1
  23.  
  24.     def generate(self, n: int):
  25.         if n < self.lastnumber: return
  26.  
  27.         for i in range(self.lastnumber, n, 2):
  28.             if self.check(i): self.primescache.append(i)
  29.  
  30.         self.lastnumber = n
  31.         if self.lastnumber % 2 == 0: self.lastnumber -= 1
  32.  
  33.     def check(self, n: int):
  34.         #if n <= self.lastnumber: return (n in self.primescache)
  35.         if n <= self.lastnumber: return (binarysearch(n,self.primescache,0,len(self.primescache)-1))
  36.  
  37.         if n < 2: return False
  38.         if n == 2: return True
  39.  
  40.         if ((n % 2) == 0) and (n > 2): return False
  41.  
  42.         for i in range(3, int(n ** 0.5), 2):
  43.             if n % i == 0:
  44.                 return False
  45.             else:
  46.                 continue
  47.  
  48.         return True
  49.  
  50.     def getlist(self, n):
  51.         list = []
  52.         self.generate(n)
  53.         for i in self.primescache:
  54.             if i <= n: list.append(i)
  55.         return list
  56.  
  57.  
  58. def getprimefactors(n):
  59.     nc = n
  60.     p1 = primes()
  61.     pf = []
  62.  
  63.     while nc > 1:
  64.         for i in p1.getlist(nc):
  65.             if nc % i == 0:
  66.                 nc /= i
  67.                 pf.append(i)
  68.                 break
  69.  
  70.     return pf
  71.  
  72.  
  73. def main():
  74.     p1 = primes()
  75.     while 1:
  76.         i = int(input())
  77.         print(getprimefactors(i))
  78.  
  79.  
  80.  
  81. if __name__ == "__main__":    main()
Add Comment
Please, Sign In to add comment