开发判断连续整数能否分解为与自身互质合数之和的函数
实现思路与代码示例
输入合法性校验
首先处理输入边界:
- 检查
a和b是否为整数类型,且不为空值 - 必须满足
1 ≤ a < b,否则直接返回"invalid choice of integers"
核心逻辑:单个整数n的验证
要判断n是否能拆分为两个与n互质的正合数之和,步骤如下:
- 最小的两个正合数之和是
4+4=8,因此小于8的n直接不符合条件 - 遍历所有可能的
x(从4到n//2),计算对应的y = n - x - 先验证
x和y都是合数(即大于1且不是质数) - 再验证
x与n互质、y与n互质(用最大公约数gcd判断,若gcd(x,n)=1则互质) - 只要存在一组符合条件的
(x,y),则n符合要求
区间遍历与结果输出
遍历区间[a,b]内的每个整数,记录所有不符合条件的数,取其中最大的那个值:
- 若存在不符合条件的数,返回格式为
"FALSE, the highest integer in the range that failed the test is c" - 若全部符合,返回
"TRUE, all integers in the range passed the test"
Python代码实现
import math def is_prime(num): # 判断是否为质数,辅助判断合数 if num <= 1: return False if num == 2: return True if num % 2 == 0: return False for i in range(3, int(math.sqrt(num)) + 1, 2): if num % i == 0: return False return True def is_valid_n(n): # 验证单个n是否符合条件 if n < 8: return False # 遍历所有可能的合数对(x, y),x <= y for x in range(4, n//2 + 1): y = n - x # 检查x和y都是合数 if not is_prime(x) and not is_prime(y): # 检查与n互质 if math.gcd(x, n) == 1 and math.gcd(y, n) == 1: return True return False def function(a, b): # 输入校验 if not (isinstance(a, int) and isinstance(b, int)): return "invalid choice of integers" if a < 1 or b <= a: return "invalid choice of integers" max_failed = None # 遍历区间内的每个数 for n in range(a, b + 1): if not is_valid_n(n): max_failed = n # 更新为当前最大的失败数 if max_failed is not None: return f"FALSE, the highest integer in the range that failed the test is {max_failed}" else: return "TRUE, all integers in the range passed the test" # 测试示例 print(function(90, 100)) # 输出: FALSE, the highest integer in the range that failed the test is 96 print(function(91, 95)) # 输出: TRUE, all integers in the range passed the test
内容的提问来源于stack exchange,提问作者JCr
相关产品推荐
相关产品推荐

