永恒的蓝色梦想 发表于 2020-4-11 12:22:29

Python 判断质数 & 质因数分解

很烂,将就着用吧from math import floor, sqrt

def isPrime(n: int, /) -> bool:
    if isinstance(n, int) and n>0:
      if n==2 or n==3:
            return True

      temp=n%6

      if n==1 or not n&1 or temp!=1 and temp!=5:
            return False

      for i in range(3,floor(sqrt(n))+1,2):
            if not n%i:
                return False

      return True

    else:
      raise TypeError("an positive integer is required")

def intFactorization(n: int, /) -> 'generator':
    if isinstance(n, int) and n>0:
      while not n&1:
            n>>=1
            yield 2
      
      temp=3
      maximum=floor(sqrt(n))

      while temp<=maximum:
            if not n%temp:
                while not n%temp:
                  n//=temp
                  yield temp

                maximum=floor(sqrt(n))

            temp+=2

      if n!=1:
            yield n

    else:
      raise TypeError("an positive integer is required")

def intFactorization(n: int, /) -> list:
    if isinstance(n, int) and n>0:
      res=[]

      while not n&1:
            n>>=1
            res.append(2)
      
      temp=3
      maximum=floor(sqrt(n))

      while temp<=maximum:
            if not n%temp:
                while not n%temp:
                  n//=temp
                  res.append(temp)

                maximum=floor(sqrt(n))

            temp+=2

      if n!=1:
            res.append(n)

      return res

    else:
      raise TypeError("an positive integer is required")
页: [1]
查看完整版本: Python 判断质数 & 质因数分解