Implementing Fibonacci and Prime Number Functions in Python
1. Fibonacci Numbers in a Given Range
This task requires implementing a function to compute Fibonacci numbers and another to count how many Fibonacci numbers lie between two given positive integers m and n (0 < m < n ≤ 100000).
The Fibonacci sequence is defined as: fib(0) = fib(1) = 1, and for any k > 1, fib(k) = fib(k-1) + fib(k-2).
Function Signature:
fib(n)— returns the n-th Fibonacci number.PrintFN(m, n)— returns a list of all Fibonacci numbers in the range [m, n].
Sample Test Program:
# 请在这里填写答案
m, n, i = input().split()
n = int(n)
m = int(m)
i = int(i)
b = fib(i)
print("fib({0}) = {1}".format(i, b))
fiblist = PrintFN(m, n)
print(len(fiblist))
Sample Input:
20 100 6
Sample Output:
fib(6) = 13
4
Implementation:
def fib(n):
"""Return the n-th Fibonacci number (with fib(0)=fib(1)=1)."""
if n == 0 or n == 1:
return 1
return fib(n-1) + fib(n-2)
def PrintFN(m, n):
"""Return a list of Fibonacci numbers in the range [m, n]."""
result = []
k = 0
while fib(k) <= n:
if fib(k) >= m:
result.append(fib(k))
k += 1
return result
Note: The recursive
fibfunction is simple but inefficient for large n. An iterative version would be better for production code.
2. Sum of Primes in a Given Range
This task requires implementing a function to check weather a number is prime, and another function to compute the sum of all prime numbers between two given positive integers x and y (x ≤ y).
Function Siganture:
isPrime(n)— returnsTrueif n is prime,Falseotherwise.primeSum(x, y)— returns the sum of all primes in the range [x, y].
Sample Test Program:
# 请在这里填写答案
x, y = map(int, input().split())
print(primeSum(x, y))
Sample Input:
2 8
Sample Output:
17
Implementation:
def isPrime(n):
"""Return True if n is a prime number, otherwise False."""
if n <= 1:
return False
for i in range(2, int(n**0.5) + 1):
if n % i == 0:
return False
return True
def primeSum(x, y):
"""Return the sum of all prime numbers in the inclusive range [x, y]."""
total = 0
for num in range(x, y + 1):
if isPrime(num):
total += num
return total
These examples demonstrate fundamental programming patterns: recursive/iterative number generation and primality testing with range summation.