优化区块链智能合约中有限斐波那契序列生成函数
The cleanest way to resolve your issues—removing unnecessary calculations, avoiding overflow, and simplifying code—is to precompute all required Fibonacci values once, then return slices of this precomputed array for any valid input.
Step 1: Precompute Fibonacci Values Up to Index 371
Since the maximum allowed index is 371 (from N+K ≤371), we can precompute the full sequence once. This avoids recalculating values for each function call and ensures we only compute each Fibonacci number exactly once.
# Precompute Fibonacci sequence up to index 371 fib = [0] * 372 fib[1] = 1 for i in range(2, 372): fib[i] = fib[i-1] + fib[i-2]
Step 2: Implement the Sequence Retrieval Function
With the precomputed array, the function becomes trivial—just return the slice from index N to N+K:
def get_fib_sequence(N, K): return fib[N:N+K]
Why This Solves Your Problems
- Eliminates unnecessary calculations: For inputs like
N=370, K=1, we directly returnfib[370]without computing any extra terms (like the out-of-rangen2). - Avoids overflow: Using arbitrary-precision integers (like Python's built-in
int) handles even the largest required value (fib[371]) without overflow. For statically typed languages (e.g., Java, C#), use big integer types (e.g.,BigInteger) during precomputation to store values beyond 256-bit limits. - Simplifies code: No extra
ifchecks or conditional logic—just a straightforward array slice. The precomputation runs once, not per function call, making the function itself extremely efficient.
Example Usage
# Get 1 element starting at N=370 print(get_fib_sequence(370, 1)) # Output: [fib(370)] # Get 5 elements starting at N=366 print(get_fib_sequence(366, 5)) # Output: [fib(366), fib(367), fib(368), fib(369), fib(370)]
For Statically Typed Languages (Example: Java)
Use BigInteger to avoid overflow and precompute values in a static initializer:
import java.math.BigInteger; import java.util.ArrayList; import java.util.List; public class FibonacciSequence { private static List<BigInteger> fib = new ArrayList<>(); static { fib.add(BigInteger.ZERO); fib.add(BigInteger.ONE); for (int i = 2; i <= 371; i++) { fib.add(fib.get(i-1).add(fib.get(i-2))); } } public static List<BigInteger> getFibSequence(int N, int K) { return fib.subList(N, N+K); } }
Content of the question originates from stack exchange, question author hitasp

