Advertisement
Guest User

Project Euler 19

a guest
Jul 17th, 2014
309
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.48 KB | None | 0 0
  1. # How many Sundays fell on the first of the month during the 20th century?
  2. # (1 Jan 1901 to 31 Dec 2000)
  3.  
  4. weekday = 0 #Weekday keeps track of what day of the week it is.
  5.             #Therefore it needs to be within {0, ..., 6}
  6.             #0 is Sunday, 1 is Monday; 6 is Saturday
  7.             #The inital condition from the problem is that the first day is a Monday
  8.  
  9. sunday_is_first = 0
  10. for year in range(1900,2001): #loops through all our years
  11.     if year == 1901:
  12.         sunday_is_first = 0
  13.     #The problem statement gives us the first weekday of 1900.
  14.     #Since we only count 1901 and onwards, we need to reset here.
  15.     for month in range(1,13): #Month 1 is January; 12 is December
  16.         weekday += 1
  17.         weekday %= 7 #Makes sure it stays within {0, ..., 6}, i.e. wraps around
  18.         if weekday == 0: #Checks if the first day of the month is indeed a Sunday
  19.             sunday_is_first += 1
  20.         if month == 4 or month == 6 or month == 9 or month == 11: weekday += 30 % 7
  21.         #4 is April, 6 is June, 9 is September, 11 is November. These months have 30 days.
  22.         #This (30 % 7) moves us to the weekday of the last day in the month.
  23.         #The modulo operation really just keeps track of what weekday the last day of the month is.
  24.         elif month == 2: #February
  25.             weekday += 28 % 7
  26.             if year % 4 == 0:
  27.                 weekday += 1 #If leap year: Adds another day to February.
  28.                 if year == 1900:
  29.                     weekday -= 1 #Centuries not divisible by 500 are _not_ leap years, thus 1900 is not.
  30.         else: weekday += 31 % 7 #The other months have 31 days.
  31.  
  32. print sunday_is_first
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement