代码需求

园宝每周收购有上限,为了最大限度换光萌园园手上星实,故用代码计算,如何卖出家园产物。

为方便计算,只考虑最多三种产物的排列组合方式。

即:列出方程coeff_a*A+coeff_b*B+coeff_c*C=n的所有自然数解(其中coeff_a、coeff_b、coeff_c、n为常数,A、B、C为自然数)。若coeff_c为0,则不参与计算。

若无自然数解,则求小于且最接近n的组合方式。

代码实现

def list_all_solutions():
    """
    列出方程 396*A + 44*B (+ 66*C) = 500000 的所有自然数解,以(A,B)或(A,B,C)格式输出
    2025.10.6:A为瓶香鱼,B为眼镜鱼,C为眼线鱼(按0.1kg)。
    """
    target = 500000
    coeff_a = 396
    coeff_b = 44
    coeff_c = 66
    
    # 根据coeff_c是否为0决定显示格式和处理方式
    if coeff_c == 0:
        print(f"方程 {coeff_a}*A + {coeff_b}*B = {target} 的所有自然数解(A,B):")
        variables = 2
    else:
        print(f"方程 {coeff_a}*A + {coeff_b}*B + {coeff_c}*C = {target} 的所有自然数解(A,B,C):")
        variables = 3
    print("=" * 50)
    
    # 寻找精确解
    solutions = find_exact_solutions(target, coeff_a, coeff_b, coeff_c, variables)
    
    # 打印精确解
    if solutions:
        print_solutions(solutions, variables)
        print(f"\n共找到 {len(solutions)} 个自然数解")
    else:
        # 如果没有找到精确解,寻找最接近但小于target的解
        print("\n未找到精确解,正在寻找最接近但小于target的解...")
        best_solution, closest_value = find_closest_solution(target, coeff_a, coeff_b, coeff_c, variables)
        
        if best_solution:
            if variables == 2:
                a, b = best_solution
                print(f"最接近但小于target的解: ({a}, {b})")
            else:
                a, b, c = best_solution
                print(f"最接近但小于target的解: ({a}, {b}, {c})")
            print(f"该解的值为: {closest_value} (目标值: {target})")
        else:
            print("未找到合适的解")

def find_exact_solutions(target, coeff_a, coeff_b, coeff_c, variables):
    """寻找方程的所有精确自然数解"""
    solutions = []
    max_b = target // coeff_b
    
    if variables == 2:
        # 两变量情况: coeff_a*A + coeff_b*B = target
        for b in range(0, max_b + 1):
            remainder = target - coeff_b * b
            if remainder >= 0 and remainder % coeff_a == 0:
                a = remainder // coeff_a
                solutions.append((a, b))
    else:
        # 三变量情况: coeff_a*A + coeff_b*B + coeff_c*C = target
        max_c = target // coeff_c
        for c in range(0, max_c + 1):
            for b in range(0, max_b + 1):
                remainder = target - coeff_c * c - coeff_b * b
                if remainder >= 0 and remainder % coeff_a == 0:
                    a = remainder // coeff_a
                    solutions.append((a, b, c))
    
    return solutions

def print_solutions(solutions, variables):
    """打印找到的解,每行10个"""
    for i, solution in enumerate(solutions):
        if variables == 2:
            print(f"({solution[0]}, {solution[1]})", end=" ")
        else:
            print(f"({solution[0]}, {solution[1]}, {solution[2]})", end=" ")
        
        if (i + 1) % 10 == 0:
            print()
    # 确保最后一行有换行
    if solutions:
        print()

def find_closest_solution(target, coeff_a, coeff_b, coeff_c, variables):
    """寻找最接近但小于target的解"""
    closest_value = 0
    best_solution = None
    
    if variables == 2:
        max_b = target // coeff_b
        max_b_search = max_b + 1000  # 扩大搜索范围
        
        for b in range(0, max_b_search + 1):
            remainder = target - coeff_b * b
            if remainder >= 0:
                a = remainder // coeff_a
                if a >= 0:
                    value = coeff_a * a + coeff_b * b
                    if value <= target and value > closest_value:
                        closest_value = value
                        best_solution = (a, b)
    else:
        max_b = target // coeff_b
        max_c = target // coeff_c
        max_b_search = max_b + 100  # 扩大搜索范围
        max_c_search = max_c + 100  # 扩大搜索范围
        
        for c in range(0, max_c_search + 1):
            for b in range(0, max_b_search + 1):
                remainder = target - coeff_c * c - coeff_b * b
                if remainder >= 0:
                    a = remainder // coeff_a
                    if a >= 0:
                        value = coeff_a * a + coeff_b * b + coeff_c * c
                        if value <= target and value > closest_value:
                            closest_value = value
                            best_solution = (a, b, c)
    
    return best_solution, closest_value

if __name__ == "__main__":
    list_all_solutions()

优化版

产物C控制在10以内,且按C的数量进行分组

def list_all_solutions():
    """
    列出方程 396*A + 189*B + 38*C = 600000 的所有自然数解(C<=10),以(A,B,C)格式输出
    2025.11.3:A-瓶香鱼(按0.1kg),B-碧露香茗茶,C-飞宝珠。
    """
    target = 600000
    # coeff_a = 396
    # coeff_b = 189
    # coeff_c = 38

    # 以下是吃了美味加成后,1.2倍的。
    coeff_a = 476
    coeff_b = 1188
    coeff_c = 106

    print(f"方程 {coeff_a}*A + {coeff_b}*B  + {coeff_c}*C = {target} 的所有自然数解(A,B,C),其中C<10:")
    print(f"目标值: {target}")
    print(f"系数: A={coeff_a}, B={coeff_b}, C={coeff_c}")
    variables = 3
    print("=" * 50)
    
    # 寻找精确解(C限制在小于10的范围内)
    solutions = find_exact_solutions(target, coeff_a, coeff_b, coeff_c, variables)
    print(f"找到的解的数量: {len(solutions)}")
    
    # 打印精确解
    if solutions:
        print_solutions(solutions, variables)
        print(f"\n共找到 {len(solutions)} 个自然数解")
    else:
        # 如果没有找到精确解,寻找最接近但小于target的解
        print("\n未找到精确解,正在寻找最接近但小于target的解...")
        best_solution, closest_value = find_closest_solution(target, coeff_a, coeff_b, coeff_c, variables)
        
        if best_solution:
            a, b, c = best_solution
            print(f"最接近但小于target的解: ({a}, {b}, {c})")
            print(f"该解的值为: {closest_value} (目标值: {target})")
        else:
            print("未找到合适的解")

def find_exact_solutions(target, coeff_a, coeff_b, coeff_c, variables):
    """寻找方程的所有精确自然数解(C限制在小于10的范围内)"""
    solutions = []
    max_b = target // coeff_b
    
    if variables == 2 or coeff_c == 0:
        # 两变量情况: coeff_a*A + coeff_b*B = target
        # 或者当coeff_c为0时,方程变为 coeff_a*A + coeff_b*B = target
        for b in range(0, max_b + 1):
            remainder = target - coeff_b * b
            if remainder >= 0 and remainder % coeff_a == 0:
                a = remainder // coeff_a
                if coeff_c == 0:
                    # 当C系数为0时,C可以是任意值,这里我们设为0
                    solutions.append((a, b, 0))
                else:
                    solutions.append((a, b))
    else:
        # 三变量情况: coeff_a*A + coeff_b*B + coeff_c*C = target
        max_c = min(10, target // coeff_c)  # 限制C小于10
        for c in range(0, max_c + 1):  # C限制在小于10的范围内
            for b in range(0, max_b + 1):
                remainder = target - coeff_c * c - coeff_b * b
                if remainder >= 0 and remainder % coeff_a == 0:
                    a = remainder // coeff_a
                    solutions.append((a, b, c))
    
    return solutions


def print_solutions(solutions, variables):
    """按C值分组打印找到的解"""
    if not solutions:
        return
        
    # 按C值分组解
    grouped_solutions = {}
    for solution in solutions:
        if variables == 2:
            # 二维情况下没有C,用0代替
            c_value = 0
        else:
            # 三维情况下C是第三个元素
            c_value = solution[2]
            
        if c_value not in grouped_solutions:
            grouped_solutions[c_value] = []
        grouped_solutions[c_value].append(solution)
    
    # 按C值顺序打印
    for c_value in sorted(grouped_solutions.keys()):
        solutions_with_same_c = grouped_solutions[c_value]
        print(f"\nC = {c_value} 时的解:")
        print("-" * 40)
        
        for i, solution in enumerate(solutions_with_same_c):
            if variables == 2:
                print(f"({solution[0]}, {solution[1]})", end=" ")
            else:
                print(f"({solution[0]}, {solution[1]}, {solution[2]})", end=" ")
            
            # 每行显示10个解
            if (i + 1) % 10 == 0:
                print()
        
        # 确保最后一行换行
        if solutions_with_same_c:
            print()
    
    print("=" * 50)

def find_closest_solution(target, coeff_a, coeff_b, coeff_c, variables):
    """寻找最接近但小于target的解(C限制在小于10的范围内)"""
    closest_value = 0
    best_solution = None
    
    if variables == 2 or coeff_c == 0:
        max_b = target // coeff_b
        max_b_search = max_b + 1000  # 扩大搜索范围
        
        for b in range(0, max_b_search + 1):
            remainder = target - coeff_b * b
            if remainder >= 0:
                a = remainder // coeff_a
                if a >= 0:
                    value = coeff_a * a + coeff_b * b
                    if value <= target and value > closest_value:
                        closest_value = value
                        if coeff_c == 0:
                            # 当C系数为0时,C可以是任意值,这里我们设为0
                            best_solution = (a, b, 0)
                        else:
                            best_solution = (a, b)
    else:
        max_b = target // coeff_b
        max_c = min(10, target // coeff_c)  # 限制C小于10
        max_b_search = max_b + 100  # 扩大搜索范围
        max_c_search = max_c + 100  # 但不超过C小于10的限制
        
        for c in range(0, min(10, max_c_search + 1)):  # 限制C小于10
            for b in range(0, max_b_search + 1):
                remainder = target - coeff_c * c - coeff_b * b
                if remainder >= 0:
                    a = remainder // coeff_a
                    if a >= 0:
                        value = coeff_a * a + coeff_b * b + coeff_c * c
                        if value <= target and value > closest_value:
                            closest_value = value
                            best_solution = (a, b, c)
    
    return best_solution, closest_value

if __name__ == "__main__":
    list_all_solutions()

Logo

Agent 垂直技术社区,欢迎活跃、内容共建。

更多推荐