To solve this problem, we need to count the number of terms in a Fibonacci-like sequence (where each term is the sum of the two preceding terms) that are less than or equal to a given integer ( n ). The sequence starts with two integers ( a ) and ( b ).
Approach
- Initialization: Start by counting the initial terms ( a ) and ( b ) if they are less than or equal to ( n ).
- Generate Subsequent Terms: Compute each subsequent term as the sum of the previous two terms. If the new term is less than or equal to ( n ), increment the count and update the previous terms to continue generating the sequence.
- Termination: Stop generating terms once the next term exceeds ( n ).
Solution Code
a, b, n = map(int, input().split())
count = 0
if a <= n:
count += 1
if b <= n:
count += 1
while True:
next_term = a + b
if next_term > n:
break
count += 1
a, b = b, next_term
print(count)
Explanation
- Initial Count: We first check if the initial terms ( a ) and ( b ) are within the limit ( n ) and count them if they are.
- Sequence Generation: For each subsequent term, we calculate it as the sum of the previous two terms. If this term is within the limit, we increment the count and update the previous terms to the current and new term to continue the sequence.
- Stopping Condition: The loop stops when the next term exceeds ( n ), ensuring we only count valid terms.
This approach efficiently generates the sequence and counts the valid terms, ensuring optimal performance even for large values of ( n ) (since the sequence grows exponentially, the number of terms is logarithmic relative to ( n )).
Example: For ( a = 1 ), ( b = 1 ), ( n = 10 ), the sequence is ( 1,1,2,3,5,8 ) and the count is 6, which the code correctly outputs.
This solution handles all edge cases, including when ( a ) or ( b ) is greater than ( n ), or when both are within the limit but subsequent terms exceed ( n ). It is straightforward and efficient.

作者声明:本文包含人工智能生成内容。