Project Euler Solution 19
#
Problem StatementHow many Sundays fell on the first of the month during the twentieth century?
You are given the following information, but you may prefer to do some research for yourself.
1 Jan 1900 was a Monday.Thirty days has September,April, June and November.All the rest have thirty-one,Saving February alone,Which has twenty-eight, rain or shine.And on leap years, twenty-nine.A leap year occurs on any year evenly divisible by 4, but not on a century unless it is divisible by 400.
How many Sundays fell on the first of the month during the twentieth century (1 Jan 1901 to 31 Dec 2000)?
#
SolutionThis problem is very simple and you can understand by just seeing the program below. Given the first January of 1900 was Monday, my first step was to find out the first day of 1901. From this we can understand that the day previous to first Jan of 1900 was Sunday. So I have initialized day=1. Oh! I have considered number for the days namely: Sunday :1, Monday :2,Tuesday : 3, Wednesday : 4, Thursday :5, Friday : 6 and Saturday : 7.
This problem is too simple. Please try :-)
#
Implementation#include <stdio.h>
int DaysInMonth(int m, int y);int main(){ int month, day, days_in_month, year, No_Sundays = 0; day = 1; month = 1; while (month <= 12) { days_in_month = DaysInMonth(month, 1900); while (days_in_month > 0) { day++; if (day == 7) day = 0; days_in_month--; } month++; } day--; for (year = 1901; year <= 2000; year++) { month = 1; while (month <= 12) { if (day == 0) No_Sundays++; days_in_month = DaysInMonth(month, year); while (days_in_month > 0) { day++; if (day == 7) day = 0; days_in_month--; } month++; } } printf("%d", No_Sundays); return 0;}int DaysInMonth(int m, int y){ int no_days; switch (m) { case 1: { no_days = 31; break; } case 2: { if (y % 400 == 0) no_days = 29; if (y % 4 == 0) no_days = 29; else no_days = 28; break; } case 3: { no_days = 31; break; } case 4: { no_days = 30; break; } case 5: { no_days = 31; break; } case 6: { no_days = 30; break; } case 7: { no_days = 31; break; } case 8: { no_days = 31; break; } case 9: { no_days = 30; break; } case 10: { no_days = 31; break; } case 11: { no_days = 30; break; } case 12: { no_days = 31; break; } } return no_days;}