Найдите следующий идентичный календарный год

Опубликовано: 19 Января, 2022

Вам дан год Y, найдите следующий календарный год, идентичный Y.
Примеры :

 Ввод: 2017 г.
Выход: 2023 г.

Ввод: 2018 г.
Выход: 2029 г.

Рекомендуется: сначала попробуйте свой подход в {IDE}, прежде чем переходить к решению.

Год x идентичен данному предыдущему году y, если выполняются следующие два условия.

  1. x начинается с того же дня, что и y.
  2. Если y високосный год, то x тоже. Если y не високосный год, то x тоже не является.

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++

// C++ program to find next identical year
#include<iostream>
using namespace std;
 
// Function for finding extra days of year
// more than complete weeks
int extraDays(int y)
{
    // If current year is a leap year, then
    // it number of weekdays move ahead by
    // 2 in terms of weekdays.
    if (y%400==0 || y%100!=0 && y%4==0)
        return 2;
 
    // Else number of weekdays move ahead
    // by 1.
    return 1;
}
 
// Returns next identical year.
int nextYear(int y)
{
    // Find number of days moved ahead by y
    int days = extraDays(y);
 
    // Start from next year
    int x = y + 1;
 
    // Count total number of weekdays
    // moved ahead so far.
    for (int sum=0; ; x++)
    {
        sum = (sum + extraDays(x)) % 7;
 
        // If sum is divisible by 7 and leap-ness
        // of x is same as y, return x.
        if ( sum==0 && (extraDays(x) == days))
            return x;
    }
 
    return x;
}
 
// driver program
int main()
{
    int y = 2018;
    cout << nextYear(y);
    return 0;
}

Java

// Java program to find next identical year
class GFG {
 
// Function for finding extra days of year
// more than complete weeks
static int extraDays(int y)
{
    // If current year is a leap year, then
    // it number of weekdays move ahead by
    // 2 in terms of weekdays.
    if (y % 400 == 0 || y % 100 != 0 && y % 4 == 0)
        return 2;
 
    // Else number of weekdays move ahead
    // by 1.
    return 1;
}
 
// Returns next identical year.
static int nextYear(int y)
{
    // Find number of days moved ahead by y
    int days = extraDays(y);
 
    // Start from next year
    int x = y + 1;
 
    // Count total number of weekdays
    // moved ahead so far.
    for (int sum = 0; ; x++)
    {
        sum = (sum + extraDays(x)) % 7;
 
        // If sum is divisible by 7 and leap-ness
        // of x is same as y, return x.
        if ( sum == 0 && (extraDays(x) == days))
            return x;
    }
 
}
 
// Driver code
public static void main(String[] args)
{
    int y = 2018;
    System.out.println(nextYear(y));
}
}
 
/* This code contributed by PrinciRaj1992 */

Python3

# Python3 program to find next identical year
 
# Function for finding extra days of year
# more than complete weeks
def extraDays(y) :
 
    # If current year is a leap year, then
    # it number of weekdays move ahead by
    # 2 in terms of weekdays.
    if (y % 400 == 0 or y % 100 != 0 and y % 4 == 0) :
        return 2
 
    # Else number of weekdays move ahead
    # by 1.
    return 1
 
# Returns next identical year.
def nextYear(y) :
 
    # Find number of days moved ahead by y
    days = extraDays(y)
 
    # Start from next year
    x = y + 1
 
    # Count total number of weekdays
    # moved ahead so far.
    Sum = 0
    while(True) :
 
        Sum = (Sum + extraDays(x)) % 7
 
        # If sum is divisible by 7 and leap-ness
        # of x is same as y, return x.
        if ( Sum == 0 and (extraDays(x) == days)) :
            return x
             
        x += 1
 
    return x
 
y = 2018
print(nextYear(y))
 
# This code is contributed by mukesh07.

C#

// C# program to find next identical year
using System;
     
class GFG
{
 
// Function for finding extra days of year
// more than complete weeks
static int extraDays(int y)
{
    // If current year is a leap year, then
    // it number of weekdays move ahead by
    // 2 in terms of weekdays.
    if (y % 400 == 0 || y % 100 != 0 && y % 4 == 0)
        return 2;
 
    // Else number of weekdays move ahead
    // by 1.
    return 1;
}
 
// Returns next identical year.
static int nextYear(int y)
{
    // Find number of days moved ahead by y
    int days = extraDays(y);
 
    // Start from next year
    int x = y + 1;
 
    // Count total number of weekdays
    // moved ahead so far.
    for (int sum = 0; ; x++)
    {
        sum = (sum + extraDays(x)) % 7;
 
        // If sum is divisible by 7 and leap-ness
        // of x is same as y, return x.
        if ( sum == 0 && (extraDays(x) == days))
            return x;
    }
 
}
 
// Driver code
public static void Main(String[] args)
{
    int y = 2018;
    Console.WriteLine(nextYear(y));
}
}
 
// This code has been contributed by 29AjayKumar

PHP

<?php
// PHP program to find
// next identical year
 
// Function for finding extra days
// of year more than complete weeks
 
function extraDays($y)
{
    // If current year is a leap year,
    // then number of weekdays move
    // ahead by 2 in terms of weekdays.
    if ($y % 400 == 0 ||
        $y % 100 != 0 &&
        $y % 4 == 0)
        return 2;
 
    // Else number of weekdays
    // move ahead by 1.
    return 1;
}
 
// Returns next identical year.
function nextYear($y)
{
    // Find number of days
    // moved ahead by y
    $days = extraDays($y);
 
    // Start from next year
    $x = $y + 1;
 
    // Count total number of weekdays
    // moved ahead so far.
    for ($sum = 0; ; $x++)
    {
        $sum = ($sum + extraDays($x)) % 7;
 
        // If sum is divisible by 7
        // and leap-ness of x is
        // same as y, return x.
        if ( $sum == 0 && (extraDays($x) == $days))
            return $x;
    }
 
    return $x;
}
 
// Driver Code
$y = 2018;
echo nextYear($y);
 
// This code is contributed by aj_36
?>

Javascript

<script>
 
// JavaScript program for the above approach
 
// Function for finding extra days of year
// more than complete weeks
function extraDays(y)
{
 
    // If current year is a leap year, then
    // it number of weekdays move ahead by
    // 2 in terms of weekdays.
    if (y % 400 == 0 || y % 100 != 0 && y % 4 == 0)
        return 2;
 
    // Else number of weekdays move ahead
    // by 1.
    return 1;
}
 
// Returns next identical year.
function nextYear(y)
{
    // Find number of days moved ahead by y
    let days = extraDays(y);
 
    // Start from next year
    let x = y + 1;
 
    // Count total number of weekdays
    // moved ahead so far.
    for (let sum = 0; ; x++)
    {
        sum = (sum + extraDays(x)) % 7;
 
        // If sum is divisible by 7 and leap-ness
        // of x is same as y, return x.
        if ( sum == 0 && (extraDays(x) == days))
            return x;
    }
 
}
 
// Driver Code
    let y = 2018;
    document.write(nextYear(y));
         
        // This code is contributed by susmitakundugoaldanga.
</script>

Выход :

2029

Эта статья предоставлена Шивамом Прадханом (anuj_charm). Если вам нравится GeeksforGeeks, и вы хотели бы внести свой вклад, вы также можете написать статью на сайте deposit.geeksforgeeks.org или отправить свою статью по электронной почте: grant@geeksforgeeks.org. Посмотрите, как ваша статья появляется на главной странице GeeksforGeeks, и помогите другим гикам.
Пожалуйста, напишите комментарии, если вы обнаружите что-то неправильное, или вы хотите поделиться дополнительной информацией по теме, обсужденной выше.

Вниманию читателя! Не прекращайте учиться сейчас. Освойте все важные концепции DSA с помощью самостоятельного курса DSA по приемлемой для студентов цене и будьте готовы к работе в отрасли. Чтобы завершить подготовку от изучения языка к DS Algo и многому другому, см. Полный курс подготовки к собеседованию .

Если вы хотите посещать живые занятия с отраслевыми экспертами, пожалуйста, обращайтесь к Geeks Classes Live и Geeks Classes Live USA.