Count of Leap Years in a given year range
Last Updated :
09 Nov, 2021
Given two years L and R, the task is to find the total number of leap years possible in the range (L, R) inclusive.
Examples:
Input: L = 1, R = 400
Output: 97
Input: L = 400, R = 2000
Output: 389
Naive Approach: The idea is to iterate through L to R and check if the year is a leap year or not using this approach.
Time complexity: O(N)
Efficient Approach:
- A year is a leap year if the following conditions are satisfied:
- Year is multiple of 400.
- Year is multiple of 4 and not multiple of 100.
- So calculate the numbers which satisfy above condition in range (1, L) and (1, R) by
Number of Leap years in (1, year) = (year / 4) – (year / 100) + (year / 400)
-
- Difference of the number of Leap years in range (1, R) with the number of leap years in range (1, L) will be the desired output.
Below is the implementation of the above approach.
C++
#include <bits/stdc++.h>
using namespace std;
int calNum( int year)
{
return (year / 4) - (year / 100) +
(year / 400);
}
void leapNum( int l, int r)
{
l--;
int num1 = calNum(r);
int num2 = calNum(l);
cout << num1 - num2 << endl;
}
int main()
{
int l1 = 1, r1 = 400;
leapNum(l1, r1);
int l2 = 400, r2 = 2000;
leapNum(l2, r2);
return 0;
}
|
Java
class GFG
{
static int calNum( int year)
{
return (year / 4 ) - (year / 100 ) +
(year / 400 );
}
static void leapNum( int l, int r)
{
l--;
int num1 = calNum(r);
int num2 = calNum(l);
System.out.print(num1 - num2 + "\n" );
}
public static void main(String[] args)
{
int l1 = 1 , r1 = 400 ;
leapNum(l1, r1);
int l2 = 400 , r2 = 2000 ;
leapNum(l2, r2);
}
}
|
Python3
def calNum(year) :
return (year / / 4 ) - (year / / 100 ) + (year / / 400 )
def leapNum(l, r) :
l - = 1
num1 = calNum(r)
num2 = calNum(l)
print (num1 - num2)
if __name__ = = "__main__" :
l1 = 1
r1 = 400
leapNum(l1, r1)
l2 = 400
r2 = 2000
leapNum(l2, r2)
|
C#
using System;
class GFG
{
static int calNum( int year)
{
return (year / 4) - (year / 100) +
(year / 400);
}
static void leapNum( int l, int r)
{
l--;
int num1 = calNum(r);
int num2 = calNum(l);
Console.Write(num1 - num2 + "\n" );
}
public static void Main(String[] args)
{
int l1 = 1, r1 = 400;
leapNum(l1, r1);
int l2 = 400, r2 = 2000;
leapNum(l2, r2);
}
}
|
Javascript
<script>
function calNum(year)
{
return parseInt(year / 4, 10) - parseInt(year / 100, 10) + parseInt(year / 400, 10);
}
function leapNum(l, r)
{
l--;
let num1 = calNum(r);
let num2 = calNum(l);
document.write((num1 - num2) + "</br>" );
}
let l1 = 1, r1 = 400;
leapNum(l1, r1);
let l2 = 400, r2 = 2000;
leapNum(l2, r2);
</script>
|
Time Complexity: O(1)
Share your thoughts in the comments
Please Login to comment...