คำนวณวันในสัปดาห์จากวันที่
โจทย์
Zeller’s congruence is an algorithm developed by Christian Zeller to calculate the data of the week. The formula is
Where
- represents the day of the week (0: Saturday, 1: Sunday, 2 Monday, 3: Tuesday, 4: Wednesday, 5: Thursday, 6: Friday)
- represents the day of the month.
- represents the month (3: March, 4: April, …, 12: December). January and February are counted as months 13 and 14 of the previous year.
- represents the century (i.e., year divided by 100).
- represents the year of the century (i.e., year mod 100).
| Input | Output |
|---|---|
| 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;
}
}
}คำอธิบาย
ปรับปรุงล่าสุด