Leap year: Difference between revisions

Content added Content deleted
(C: optimize, extend tests)
Line 1,351: Line 1,351:
<syntaxhighlight lang="c">#include <stdio.h>
<syntaxhighlight lang="c">#include <stdio.h>


int is_leap_year(int year)
int is_leap_year(unsigned year)
{
{
return (!(year % 4) && year % 100 || !(year % 400)) ? 1 : 0;
return !(year & (year % 100 ? 3 : 15));
}
}


int main()
int main(void)
{
{
int test_case[] = {1900, 1994, 1996, 1997, 2000}, key, end, year;
const unsigned test_case[] = {
1900, 1994, 1996, 1997, 2000, 2024, 2025, 2026, 2100
for (key = 0, end = sizeof(test_case)/sizeof(test_case[0]); key < end; ++key) {
};
year = test_case[key];
const unsigned n = sizeof test_case / sizeof test_case[0];
printf("%d is %sa leap year.\n", year, (is_leap_year(year) == 1 ? "" : "not "));

for (unsigned i = 0; i != n; ++i) {
unsigned year = test_case[i];
printf("%u is %sa leap year.\n", year, is_leap_year(year) ? "" : "not ");
}
}
return 0;
}</syntaxhighlight>
}</syntaxhighlight>
{{out}}
{{out}}
Line 1,371: Line 1,376:
1997 is not a leap year.
1997 is not a leap year.
2000 is a leap year.
2000 is a leap year.
2024 is a leap year.
2025 is not a leap year.
2026 is not a leap year.
2100 is not a leap year.
</pre>
</pre>