#T568. 过生日
过生日
Description
Xiao Ming was born in a leap year, and he wants to know when he can celebrate his birthday. Can you tell him?
Given a positive integer Y, representing the starting year, and a positive integer N, your task is to determine the Nth leap year starting from year Y.
Note: If Y itself is a leap year, then the first leap year is Y.
Input Format
The first line of input is an integer T, representing the number of test cases.
Each test case consists of two positive integers Y and N (1 ≤ N ≤ 10000).
Output Format
For each test case, output the Nth leap year starting from year Y.
Example
Input:
3
2000 5
2001 4
2002 3
Output:
2016
2008
2008
Explanation
-
For the first test case (2000, 5):
Starting from 2000 (a leap year), the sequence of leap years is 2000, 2004, 2008, 2012, 2016. The 5th leap year is 2016. -
For the second test case (2001, 4):
Starting from 2001 (not a leap year), the sequence of leap years is 2004, 2008, 2012, 2016. The 4th leap year is 2008. -
For the third test case (2002, 3):
Starting from 2002 (not a leap year), the sequence of leap years is 2004, 2008, 2012. The 3rd leap year is 2008.
Constraints
- 1 ≤ T ≤ 100
- 1 ≤ Y ≤ 10000
- 1 ≤ N ≤ 10000
Solution
To solve this problem, we need to find the Nth leap year starting from a given year Y. A leap year is defined as a year that is divisible by 4, but not divisible by 100 unless it is also divisible by 400.
Approach:
- Check for Leap Year: For a given year, determine if it is a leap year.
- Iterate Through Years: Starting from year Y, check each subsequent year to see if it is a leap year until we have found N leap years.
- Output the Result: Once N leap years are found, output the Nth one.
Key Steps:
- If the starting year Y is a leap year, it counts as the first leap year.
- For each subsequent year, incrementally check if it meets the leap year criteria.
- Continue this process until N leap years are identified.
This approach efficiently checks each year in sequence, ensuring correctness by adhering to the leap year rules.
Code
def is_leap(year):
if year % 4 != 0:
return False
elif year % 100 != 0:
return True
else:
return year % 400 == 0
T = int(input())
for _ in range(T):
Y, N = map(int, input().split())
count = 0
current_year = Y
while count < N:
if is_leap(current_year):
count += 1
if count == N:
break
current_year += 1
print(current_year)
Explanation of the Code:
- The function
is_leapchecks whether a given year is a leap year based on the specified rules. - For each test case, the code initializes the count of leap years found and starts checking from year Y.
- It increments the year until N leap years are found, then prints the Nth leap year.
This solution efficiently handles the constraints and provides the correct result for each test case.
3
2005 25
1855 12
2004 10000
2108
1904
43236
## Source
CodesOnline