Find the next identical calendar year
You are given an year Y, find the next identical calendar year to Y.
Examples :
Input : 2017
Output : 2023
Input : 2018
Output : 2029
An year x is identical to a given previous year y if following two conditions are satisfied.
- x starts with same day as y.
- If y is leap year, then x is also. If y is not leap year, then x is also not.
The idea is to check all years one by one (starting from next year). We keep track of number of days moved ahead. If total moved days is 7, then current year begins with same day. We also check if leap-ness of current year is same as y. If both conditions are satisfied, we return current year.
C++
#include<iostream>
using namespace std;
int extraDays( int y)
{
if (y%400==0 || y%100!=0 && y%4==0)
return 2;
return 1;
}
int nextYear( int y)
{
int days = extraDays(y);
int x = y + 1;
for ( int sum=0; ; x++)
{
sum = (sum + extraDays(x)) % 7;
if ( sum==0 && (extraDays(x) == days))
return x;
}
return x;
}
int main()
{
int y = 2018;
cout << nextYear(y);
return 0;
}
|
Java
class GFG {
static int extraDays( int y)
{
if (y % 400 == 0 || y % 100 != 0 && y % 4 == 0 )
return 2 ;
return 1 ;
}
static int nextYear( int y)
{
int days = extraDays(y);
int x = y + 1 ;
for ( int sum = 0 ; ; x++)
{
sum = (sum + extraDays(x)) % 7 ;
if ( sum == 0 && (extraDays(x) == days))
return x;
}
}
public static void main(String[] args)
{
int y = 2018 ;
System.out.println(nextYear(y));
}
}
|
Python3
def extraDays(y) :
if (y % 400 = = 0 or y % 100 ! = 0 and y % 4 = = 0 ) :
return 2
return 1
def nextYear(y) :
days = extraDays(y)
x = y + 1
Sum = 0
while ( True ) :
Sum = ( Sum + extraDays(x)) % 7
if ( Sum = = 0 and (extraDays(x) = = days)) :
return x
x + = 1
return x
y = 2018
print (nextYear(y))
|
C#
using System;
class GFG
{
static int extraDays( int y)
{
if (y % 400 == 0 || y % 100 != 0 && y % 4 == 0)
return 2;
return 1;
}
static int nextYear( int y)
{
int days = extraDays(y);
int x = y + 1;
for ( int sum = 0; ; x++)
{
sum = (sum + extraDays(x)) % 7;
if ( sum == 0 && (extraDays(x) == days))
return x;
}
}
public static void Main(String[] args)
{
int y = 2018;
Console.WriteLine(nextYear(y));
}
}
|
PHP
<?php
function extraDays( $y )
{
if ( $y % 400 == 0 ||
$y % 100 != 0 &&
$y % 4 == 0)
return 2;
return 1;
}
function nextYear( $y )
{
$days = extraDays( $y );
$x = $y + 1;
for ( $sum = 0; ; $x ++)
{
$sum = ( $sum + extraDays( $x )) % 7;
if ( $sum == 0 && (extraDays( $x ) == $days ))
return $x ;
}
return $x ;
}
$y = 2018;
echo nextYear( $y );
?>
|
Javascript
<script>
function extraDays(y)
{
if (y % 400 == 0 || y % 100 != 0 && y % 4 == 0)
return 2;
return 1;
}
function nextYear(y)
{
let days = extraDays(y);
let x = y + 1;
for (let sum = 0; ; x++)
{
sum = (sum + extraDays(x)) % 7;
if ( sum == 0 && (extraDays(x) == days))
return x;
}
}
let y = 2018;
document.write(nextYear(y));
</script>
|
Output :
2029
Last Updated :
13 Sep, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...