Problem specification: ProjectEuler.net Problem 19
Need to calculate how many Sundays fall on the first of each month between 1900 and 2000.
This method is just simple maths. I use an array to represent the number of days in a month, which also means I can manipulate the entry for Feb on leap years. Simple addition of an array elements value each time, and remainder by 7. If a zero, it is a Sunday. Initialise curday to 2, as the 1st of Jan 1901 was a Tuesday.
Execution time: <1ms (laptop)
CODE
package projecteuler;
/**
* Project euler problem 19 java solution
* @author Mike
*/
public class Project19 {
public static void main(String[] args){
int sundays = 0;
int curday = 2;
int years = 1901;
int[] daysInMonth = {31,28,31,30,31,30,31,31,30,31,30,31};
while(years < 2001){
// we go around 100 years.
daysInMonth[1] = 28;
if(years % 100 == 0){
if(years % 400 == 0){
daysInMonth[1] = 29;
} else {
daysInMonth[1] = 28;
}
} else if(years % 4 == 0){
daysInMonth[1] = 29;
}
for(int j = 0; j < daysInMonth.length; j++){
curday += daysInMonth[j];
if(curday % 7 == 0){
sundays++;
}
}
years++;
}
System.out.println(sundays);
}
}
Any suggestions and comments are welcome, please send me an email (see contacts).