- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Find the next identical calendar year in C++
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
#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
Advertisements
To Continue Learning Please Login
Login with Google