Prolog中series/2谓词实现求助:求解指定数列第N项
Hey there! Let's work through this Prolog exercise together—no worries, it's easier once we spot the pattern in the sequence.
series/2 Prolog Predicate First, let's break down the pattern in the given sequence: 3, 7, 15, 31...
- For N=1: 3 = 2^(1+1) - 1 = 4 - 1
- For N=2: 7 = 2^(2+1) - 1 = 8 - 1
- For N=3: 15 = 2^(3+1) - 1 = 16 - 1
- For N=4: 31 = 2^(4+1) - 1 = 32 - 1
The core rule here is Ans = 2^(N+1) - 1. We can implement this in Prolog in two common ways—let's cover both:
Option 1: Direct Mathematical Calculation
Using Prolog's built-in arithmetic predicates, we can compute the value directly with the formula. We'll also add a check to ensure N is a positive integer (since we're referring to the Nth term of a sequence):
series(N, Ans) :- integer(N), N > 0, Ans is 2^(N+1) - 1.
Testing this implementation:
series(1, X).returnsX = 3series(3, X).returnsX = 15series(4, X).returnsX = 31
Option 2: Recursive Implementation
If you want to focus on how the sequence builds incrementally (a common approach in Prolog), we can use recursion with a base case and recursive step. Notice each term is the previous term multiplied by 2 plus 1:
- 3 * 2 + 1 = 7 (2nd term)
- 7 * 2 + 1 = 15 (3rd term)
- 15 * 2 + 1 = 31 (4th term)
Here's the recursive code:
% Base case: The 1st term is 3 series(1, 3). % Recursive step: Calculate current term from the previous one series(N, Ans) :- N > 1, PrevN is N - 1, series(PrevN, PrevAns), Ans is PrevAns * 2 + 1.
This will produce the exact same results as the formula-based version, and it's great for understanding the sequence's iterative logic.
Quick Notes
- Both implementations validate that N is a positive integer to avoid invalid inputs (like 0 or negative numbers).
- The formula-based version is more efficient for large values of N, while the recursive version is helpful for learning how sequences can be defined step-by-step in Prolog.
内容的提问来源于stack exchange,提问作者Walker

