It is given to you that on 1st January 2001 it was Monday. Let’s call a year as Geeky if the 1st January of that year happens to be on Sunday. There will be given two years ‘a‘ and ‘b‘. The task is to find the no. of Geeky years between those two years (including ‘a’ and ‘b’ as well)
Examples:
Input: a = 2001, b = 2013
Output: 2
Input: a = 2020, b = 2024
Output: 1
Approach: The idea is to store the days shift for each month and then calculate the answer. Follow the steps below to solve the problem:
- Initialize the variable count as 0.
- Iterate over the range [a, b] using the variable i and perform the following tasks:
- Initialize the variable y as i-1.
- Initialize the variable ans as (y + y / 4 – y / 100 + y / 400) % 7.
- If ans equals 6 then increase the value of count by 1.
- After performing the above steps, print the value of count as the answer.
Below is the implementation of the above approach.
C++
#include <bits/stdc++.h>
using namespace std;
int Count( int a, int b)
{
int t[] = { 0, 3, 2, 5, 0, 3,
5, 1, 4, 6, 2, 4 };
int count = 0;
for ( int i = a; i <= b; i++) {
int y = i - 1;
int ans = (y + y / 4 - y / 100 + y / 400) % 7;
if (ans == 6) {
count++;
}
}
return count;
}
int main()
{
int a = 2001;
int b = 2013;
int ans = Count(a, b);
cout << ans;
}
|
Java
import java.io.*;
import java.lang.*;
import java.util.*;
class GFG {
public static int Count( int a, int b)
{
int t[] = { 0 , 3 , 2 , 5 , 0 , 3 ,
5 , 1 , 4 , 6 , 2 , 4 };
int count = 0 ;
for ( int i = a; i <= b; i++) {
int y = i - 1 ;
int ans = (y + y / 4
- y / 100 + y / 400 )
% 7 ;
if (ans == 6 ) {
count++;
}
}
return count;
}
public static void main(String[] args)
{
int a = 2001 ;
int b = 2013 ;
int ans = Count(a, b);
System.out.println(ans);
}
}
|
Python3
def Count(a, b):
t = [ 0 , 3 , 2 , 5 , 0 , 3 ,
5 , 1 , 4 , 6 , 2 , 4 ]
count = 0
for i in range (a, b + 1 ):
y = i - 1
ans = (y + y / / 4 - y / / 100 + y / / 400 ) % 7
if (ans = = 6 ):
count + = 1
return count
if __name__ = = "__main__" :
a = 2001
b = 2013
ans = Count(a, b)
print (ans)
|
C#
using System;
class GFG {
public static int Count( int a, int b)
{
int []t = { 0, 3, 2, 5, 0, 3,
5, 1, 4, 6, 2, 4 };
int count = 0;
for ( int i = a; i <= b; i++) {
int y = i - 1;
int ans = (y + y / 4
- y / 100 + y / 400)
% 7;
if (ans == 6) {
count++;
}
}
return count;
}
public static void Main()
{
int a = 2001;
int b = 2013;
int ans = Count(a, b);
Console.WriteLine(ans);
}
}
|
Javascript
<script>
function Count(a, b) {
let t = [0, 3, 2, 5, 0, 3,
5, 1, 4, 6, 2, 4];
let count = 0;
for (let i = a; i <= b; i++) {
let y = i - 1;
let ans = (y + Math.floor(y / 4)
- Math.floor(y / 100) + Math.floor(y / 400))
% 7;
if (ans == 6) {
count++;
}
}
return count;
}
let a = 2001;
let b = 2013;
let ans = Count(a, b);
document.write(ans);
</script>
|
Time Complexity: O(N)
Auxiliary Space: O(1)
Last Updated :
17 Jan, 2022
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...