Find the next identical calendar year in C++

C++Server Side ProgrammingProgramming

Suppose we have an year Y. Find next identical calendar year to Y. So the calendar of 2017 is identical with 2023.

A year X is identical to given previous year Y if it matches these two conditions.

  • x starts with the same day as year,
  • If y is leap year, then x also, if y is normal year, then x also normal year.

The idea is to check all years one by one from next year. We will keep track of number of days moved ahead. If there are total 7 moved days, then current year begins with same day. We also check if the current year is leap year or not, if so, then also check for y. If both conditions are satisfied, we return current year.

Example

 Live Demo

#include<iostream>
using namespace std;
int countExtraDays(int y) {
   if (y%400==0 || y%100!=0 && y%4==0)
   return 2;
   return 1;
}
int nextIdenticalYear(int y) {
   int days = countExtraDays(y);
   int x = y + 1;
   for (int sum=0; ; x++) {
      sum = (sum + countExtraDays(x)) % 7;
      if ( sum==0 && (countExtraDays(x) == days))
      return x;
   }
   return x;
}
int main() {
   int curr = 2019;
   cout << "Next identical year of " << curr <<" is: " << nextIdenticalYear(curr);
}

Output

Next identical year of 2019 is: 2030
raja
Published on 19-Dec-2019 12:52:35
Advertisements