Problem 19. Counting Sundays

Description

public class euler19 {
    public static void main(String[]args) {
        int n = 7;
       	int count = 0;
       	int month = 1;
        int k = 0;
        for (int i = 1901; i < 2001; i++) {
            month = 1;
            while (month < 13) {
           	n += 28;
               	switch (month) {
               	case 1: case 3: case 5: case 7: case 8: case 10: case 12:
            	    if (n < 32) {
             	        n += 7;
                        n -= 31;
                        if (i > 1900 && n == 2) {
                            count++;
                        }
                    }
                    else {
                        n -= 31;
                        if (i > 1900 && n == 2) {
                             count++;
                        }
                    }
                    break;
                case 4: case 6: case 9: case 11:
                    if (n < 31) {
                        n += 7;
                        n -= 30;
                        if (i > 1900 && n == 2) {
                            count++;
                        }
                    }
                    else {
                        n -= 30;
                        if (i > 1900 && n == 2) {
                            count++;
                        }
                    }
                    break;
              	case 2: 
                    if (((i % 4 == 0) && !(i % 100 == 0)) || i % 400 == 0) 
                        k = 29;
                    else
                        k = 28;
                    if (n < k+1) {
                        n += 7;
                        n -= k;
                        if (i > 1900 && n == 2) {
                            count++;
                        }
                    }
               	    else {
                        n -= k;
                        if (i > 1900 && n == 2) {
                            count++;
                      	}
                    }
               	    break;
             	}
                month++;
            } // end of while
        } // end of for
        System.out.println(count);
    }
}

Leave a Reply

Your email address will not be published. Required fields are marked *

*

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>