You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

编写Prolog程序:判断列表中是否存在三个元素之和等于N

Prolog Program to Check for Exactly Three Elements Summing to N

Hey there! Let's put together a clean Prolog solution to check if a given list has exactly three distinct elements that add up to a specified number N.

Approach

The core idea is to pick three unique elements from the list (so we don't reuse the same element multiple times) and verify if their sum matches N. We'll use Prolog's built-in select/3 predicate to safely extract elements one by one—this ensures each element comes from the remaining part of the list after the previous selection, avoiding duplicates.

Solution Code

% Main predicate: Checks if three distinct elements in List sum to N
three_sum(List, N) :-
    % Pick first element A, leaving the rest of the list as Rest1
    select(A, List, Rest1),
    % Pick second element B from Rest1, leaving Rest2
    select(B, Rest1, Rest2),
    % Pick third element C from Rest2
    select(C, Rest2, _),
    % Verify the sum of A, B, C equals N
    A + B + C =:= N.

How It Works

  • select(A, List, Rest1): Removes element A from the original list, giving us Rest1—this guarantees A is part of the list and won't be picked again.
  • select(B, Rest1, Rest2): Pulls B from the remaining list Rest1, ensuring it's a different element than A.
  • select(C, Rest2, _): Extracts C from Rest2, making sure it's distinct from both A and B.
  • Finally, A + B + C =:= N checks if the arithmetic sum of the three elements matches our target number.

Test Cases

Let's validate with your examples:

  1. For List = [1,2,3,4,5,6] and N = 6:

    ?- three_sum([1,2,3,4,5,6], 6).
    true.
    

    This returns true because 1 + 2 + 3 = 6.

  2. For List = [2,5,7,9] and N = 12:

    ?- three_sum([2,5,7,9], 12).
    false.
    

    All possible triplets sum to 14, 16, 18, or 21—none equal 12, so we get false.

Quick Note

If you ever need to allow reusing the same element multiple times (like checking if three 2s sum to 6 in [2,3]), you can swap select/3 with member/2 instead. But based on your examples, the distinct-element approach is exactly what you need.

内容的提问来源于stack exchange,提问作者SpaceCow

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 09:36:30