# [Golang] Counting Sundays - Problem 19 - Project Euler

Problem: [1]

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)?

Solution:

171

Run Code on Go Playground

package main

import (
"fmt"
)

func monthDays(year, month int) int {
switch month {
case 1, 3, 5, 7, 8, 10, 12:
return 31
case 4, 6, 9, 11:
return 30
case 2:
if year%400 == 0 {
return 29
}
if year%100 == 0 {
return 28
}
if year%4 == 0 {
return 29
}
return 28
}
panic("not correct month")
}

func main() {
year := 1900
month := 1
day := 1
weekDay := 1 // 1: Monday ... 7: Sunday

count := 0
for {
day += 1
if day > monthDays(year, month) {
day = 1
month += 1
}
if month > 12 {
month = 1
year += 1
}

weekDay += 1
if weekDay > 7 {
weekDay = 1
}

// first day of the month is Sunday
if day == 1 && weekDay == 7 && year > 1900 {
//fmt.Printf("%d %d 1st is Sunday\n", year, month)
count += 1
}

// termination condition
if year == 2000 && month == 12 && day == 31 {
break
}
}

fmt.Printf("total %d Sunday", count)
}

Test on:

References: