Skip to Content
CoursesCSC122คำนวณวันในสัปดาห์จากวันที่

คำนวณวันในสัปดาห์จากวันที่

โจทย์

Zeller’s congruence is an algorithm developed by Christian Zeller to calculate the data of the week. The formula is

h=(q+(26×(m+1)10)+k+(k4)+(j4)+(5×j))mod7h = \left(q + \left(\frac{26 \times (m + 1)}{10}\right) + k + \left(\frac{k}{4}\right) + \left(\frac{j}{4}\right) + (5 \times j)\right) \mod 7

Where

  • hh represents the day of the week (0: Saturday, 1: Sunday, 2 Monday, 3: Tuesday, 4: Wednesday, 5: Thursday, 6: Friday)
  • qq represents the day of the month.
  • mm represents the month (3: March, 4: April, …, 12: December). January and February are counted as months 13 and 14 of the previous year.
  • jj represents the century (i.e., year divided by 100).
  • kk represents the year of the century (i.e., year mod 100).
InputOutput
2024
8
28
Wednesday

โค้ด

import java.util.*; public class Program { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int year = scanner.nextInt(); int month = scanner.nextInt(); int day = scanner.nextInt(); year = month == 1 || month == 2 ? year - 1 : year; month = month == 1 || month == 2 ? month + 12 : month; int j = year / 100; int k = year % 100; int h = (day + ((26 * (month + 1)) / 10) + k + (k / 4) + (j / 4) + (5 * j)) % 7; switch (h) { case 0: System.out.println("Saturday"); break; case 1: System.out.println("Sunday"); break; case 2: System.out.println("Monday"); break; case 3: System.out.println("Tuesday"); break; case 4: System.out.println("Wednesday"); break; case 5: System.out.println("Thursday"); break; case 6: System.out.println("Friday"); break; } } }

คำอธิบาย

ปรับปรุงล่าสุด