求数组中重复次数最多的质数:算法实现求助(附现有代码)
找出数组中重复次数最多的质数(无字典实现)
问题描述
给定一个包含重复数值的数组,需确定其中重复次数最多的质数,且禁止使用字典,要求代码风格与提供的初始代码一致。
初始代码问题分析
你提供的代码存在几个关键问题:
- 输入的元素未转换为整数类型,导致后续取余运算出错
- 质数判断逻辑错误:质数的定义是仅能被1和自身整除,你的循环中
c2 < A[c],对于质数来说只有1能整除它,cm应该等于1而非2 - 仅记录了最后一个质数,未统计每个质数的重复次数,无法找出重复最多的那个
修正后的解决方案
# 获取数组长度和元素 cd = int(input("Enter the number of elements: ")) A = [] for i in range(cd): el = int(input("")) # 转换为整数类型,避免运算错误 A.append(el) # 第一步:筛选数组中所有质数,存入质数列表 prime_list = [] c = 0 while c < cd: num = A[c] # 小于2的数直接排除,不是质数 if num < 2: c += 1 continue cm = 0 c2 = 1 while c2 <= num: if num % c2 == 0: cm += 1 c2 += 1 # 质数仅存在1和自身两个因数 if cm == 2: prime_list.append(num) c += 1 # 第二步:找出质数列表中重复次数最多的数 if not prime_list: print("数组中没有质数") else: max_count = 0 most_frequent_prime = prime_list[0] c = 0 while c < len(prime_list): current_prime = prime_list[c] current_count = 0 # 统计当前质数的出现次数 c2 = 0 while c2 < len(prime_list): if prime_list[c2] == current_prime: current_count += 1 c2 += 1 # 更新最大次数和对应质数 if current_count > max_count: max_count = current_count most_frequent_prime = current_prime # 跳过已统计过的质数,避免重复计算 while c < len(prime_list) and prime_list[c] == current_prime: c += 1 print(f"重复次数最多的质数是 {most_frequent_prime},共出现 {max_count} 次")
关键逻辑说明
- 质数筛选:遍历原数组,判断每个数的因数个数是否为2,符合条件的存入质数列表
- 次数统计:用嵌套循环统计每个质数的出现次数,同时跳过已统计的质数减少重复运算
- 边界处理:如果数组中没有质数,会直接给出提示
内容的提问来源于stack exchange,提问作者SirMrpirateroberts
相关产品推荐
相关产品推荐

