鱼C论坛

 找回密码
 立即注册
查看: 986|回复: 0

[作品展示] Python 判断质数 & 质因数分解

[复制链接]
发表于 2020-4-11 12:22:29 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

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

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

  6.         temp=n%6

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

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

  12.         return True

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

  15. def intFactorization(n: int, /) -> 'generator':
  16.     if isinstance(n, int) and n>0:
  17.         while not n&1:
  18.             n>>=1
  19.             yield 2
  20.         
  21.         temp=3
  22.         maximum=floor(sqrt(n))

  23.         while temp<=maximum:
  24.             if not n%temp:
  25.                 while not n%temp:
  26.                     n//=temp
  27.                     yield temp

  28.                 maximum=floor(sqrt(n))

  29.             temp+=2

  30.         if n!=1:
  31.             yield n

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

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

  37.         while not n&1:
  38.             n>>=1
  39.             res.append(2)
  40.         
  41.         temp=3
  42.         maximum=floor(sqrt(n))

  43.         while temp<=maximum:
  44.             if not n%temp:
  45.                 while not n%temp:
  46.                     n//=temp
  47.                     res.append(temp)

  48.                 maximum=floor(sqrt(n))

  49.             temp+=2

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

  52.         return res

  53.     else:
  54.         raise TypeError("an positive integer is required")
复制代码
小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2025-6-12 20:44

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表