How to Print the Next N Leap Years in Java?
Last Updated :
28 May, 2021
Concept: The basic assertion in problem-solving for the leap year is an interval of 4 years which is wrong in itself. For any random year in the calendar to be a leap year it must hold below conditions. Now if the year is a leap year the goal is simply to print the consecutive same kinds of years in a calendar year that is all years should be leap year prior or adhering the leap year to be taken into consideration to illustrate and implement the same.
Approach: Problem-solving is simple to break into two halves. The first half is the focus to figure out a leap year or not and writing the code for the same. The second half simply emphasis to maintain a count whenever leap year is encountered and synchronized with the first half.
Mandatory conditions to be satisfied for a year to refer as a leap year
- The year should be multiple of 400.
- The year should be a multiple of 4 and should not a multiple of 100.
Algorithm:
- Condition checking divisibility with 4- If the number is divisible by 4 the check will proceed further and if the number is not divisible by 4 then for sure not a leap year.
- Condition checking divisibility with 100-The year obtained here is already divisible by 4.Now further if the year satisfies the above condition then if the year is divisible by 100, the year proceeds for further conditionality check. If the number is not divisible by 100 then for sure not a leap year.
- Condition checking divisibility with 400- The year obtained here is already divisible by 4 and 100. Now further if the year is divisible by 400 then for sure a leap year else for sure not a leap year.
- As of now the year obtained here is a Leap year, the approach to print leap year is very simple
- Initializing a variable with zero to maintain lap year count
- Incrementing the count when it is for sure that the year is a leap year
- Iterating taking count into consideration for condition statement and where the condition fails out simply return all the years that satisfied the condition previously.
Illustration:
Input 1: year = 2020, N = 15
Output: 2024
2028
2032
2036
2040
2044
2048
2052
2056
2060
2064
2068
2072
2076
2080
Input 2: year = 2022, N = 2
Output: 2024
2028
Implementation: Below is the example to illustrate the above illustration in Java:
Java
import java.io.*;
class GFG {
public static void main(String[] args)
{
int year = 2020 ;
int n = 15 ;
int count = 0 ;
while (count != n)
{
year = year + 1 ;
if ((year % 400 == 0 )
|| (year % 4 == 0 && year % 100 != 0 )) {
count++;
System.out.println(year);
}
}
}
}
|
Output
2024
2028
2032
2036
2040
2044
2048
2052
2056
2060
2064
2068
2072
2076
2080
Share your thoughts in the comments
Please Login to comment...