当前位置: 首页 > java >正文

质数、因数、最大公约数经典问题整理

1、计数质数

MX = 5000000
is_prime = [1] * MX
is_prime[0] = is_prime[1]= 0
for i in range(2, MX):if is_prime[i]:for j in range(i * i, MX, i):is_prime[j] = 0class Solution:def countPrimes(self, n: int) -> int:return sum(is_prime[:n])

2、序列中不同最大公约数的数目

class Solution:def countDifferentSubsequenceGCDs(self, nums: List[int]) -> int:ans, mx = 0, max(nums)has = [False] * (mx + 1)for x in nums: has[x] = Truefor i in range(1, mx + 1):g = 0  # 0 和任何数 x 的最大公约数都是 xfor j in range(i, mx + 1, i):  # 枚举 i 的倍数 jif has[j]:  # 如果 j 在 nums 中g = gcd(g, j)  # 更新最大公约数if g == i:  # 找到一个答案(g 无法继续减小)ans += 1break  # 提前退出循环return ans

 3、子数组的最大 GCD-Sum

利用子数组gcd值为有限个的情况(复杂度为lgn),对每个gcd值使用最大长度数组进行匹配

class Solution:def maxGcdSum(self, nums: List[int], k: int) -> int:maxl = 0pre = [0]for num in nums:pre.append(pre[-1] + num)g = deque()for i, num in enumerate(nums):temp, s, si = deque(), num, iwhile g:n2, j = g.pop()if gcd(n2, s) < s:temp.appendleft((s, si))if i - si + 1 >= k:maxl = max(maxl, (pre[i + 1] - pre[si]) * s)s, si = gcd(n2, s), jelse:si = jelse:temp.appendleft((s, si))if i - si + 1 >= k:maxl = max(maxl, (pre[i + 1] - pre[si]) * s)g = tempreturn maxl
找到最接近目标值的函数值 与上述做法类似,利用子数组与运算结果为有限个(lgn)的性质,代码如下:
class Solution:def closestToTarget(self, arr: List[int], target: int) -> int:ans = abs(arr[0] - target)valid = {arr[0]}for num in arr:valid = {x & num for x in valid} | {num}ans = min(ans, min(abs(x - target) for x in valid))return ans

4、n 的第 k 个因子

class Solution:def kthFactor(self, n: int, k: int) -> int:count = 0factor = 1while factor * factor <= n:if n % factor == 0:count += 1if count == k:return factorfactor += 1factor -= 1if factor * factor == n:factor -= 1while factor > 0:if n % factor == 0:count += 1if count == k:return n // factorfactor -= 1return -1

5、分解质因数 --  分割数组使乘积互质

class Solution:def findValidSplit(self, nums: List[int]) -> int:left = {}  # left[p] 表示质数 p 首次出现的下标right = [0] * len(nums)  # right[i] 表示左端点为 i 的区间的右端点的最大值def f(p: int, i: int) -> None:if p in left:right[left[p]] = i  # 记录左端点 l 对应的右端点的最大值else:left[p] = i  # 第一次遇到质数 pfor i, x in enumerate(nums):d = 2while d * d <= x:  # 分解质因数if x % d == 0:f(d, i)x //= dwhile x % d == 0:x //= dd += 1if x > 1: f(x, i)max_r = 0for l, r in enumerate(right):if l > max_r:  # 最远可以遇到 max_rreturn max_r  # 也可以写 l-1max_r = max(max_r, r)return -1

使用前缀和 --  向下取整数对和、 统计美丽子字符串 II

6、统计可以被 K 整除的下标对数目

class Solution:def countPairs(self, nums: List[int], k: int) -> int:mx = max(max(nums), k)cnt = [0] * (mx + 1)for num in nums:cnt[num] += 1#统计每个数的倍数出现的次数for i in range(1, mx + 1):for j in range(2 * i, mx + 1, i):cnt[i] += cnt[j]res = 0for num in nums:res += cnt[k // gcd(k, num)]for num in nums:if num * num % k == 0:res -= 1return res // 2

  

http://www.xdnf.cn/news/16318.html

相关文章:

  • KNN 算法进阶:从基础到优化的深度解析
  • lesson24:Python的logging模块
  • 将文件移入回收站而不是直接删除
  • 7月25号打卡
  • 太极生两仪,两仪生四象,四象生八卦
  • 13.使用C连接mysql
  • Windows Server 2003 R2系统C盘扩容教程
  • 【深度学习新浪潮】Claude code是什么样的一款产品?
  • 【Linux系统】基础IO(下)
  • 常见问题三
  • linux 进程信号
  • 佳能iR-ADV C5560复印机如何扫描文件到电脑
  • Gorm教程 - 关联
  • 电厂液压执行器自动化升级:Modbus TCP与DeviceNet的协议贯通实践
  • 微观低代码
  • SpringBoot实战指南:从快速入门到生产级部署(2025最新版)
  • 【运维】ubuntu 安装图形化界面
  • Vue2下
  • SQLFluff
  • Hive-vscode-snippets
  • [特殊字符] 第9篇:《SQL高阶 SELECT 技巧:DISTINCT、ORDER BY、LIMIT 全家桶》
  • CN3798-2A 降压型单节锂电池充电芯片
  • Androidstudio 上传当前module 或本地jar包到maven服务器。
  • 二分查找----6.寻找两个正序数组的中位数
  • Python 数据分析(一):NumPy 基础知识
  • PI 思维升级 PI设计的典范转移:从阻抗思维到谐振控制
  • 【办公类-107-03】20250725通义万相2.1“动物拟人化”视频,优化关键词(图片转视频MP4转gif))
  • 我的世界之战争星球 暮色苍茫篇 第二十三章、出发!暮色森林!
  • 【硬件-笔试面试题】硬件/电子工程师,笔试面试题-26,(知识点:硬件电路的调试方法:信号追踪,替换,分段调试)
  • 恋爱时间倒计时网页设计与实现方案