Project Euler > Problem 19 > Counting Sundays (Java Solution)

Problem:

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


Code:
The solution may include methods that will be found here: Library.java .

public interface EulerSolution{

public String run();

}
/* 
 * Solution to Project Euler problem 19
 * By Nayuki Minase
 * 
 * http://nayuki.eigenstate.org/page/project-euler-solutions
 * https://github.com/nayuki/Project-Euler-solutions
 */


public final class p019 implements EulerSolution {
 
 public static void main(String[] args) {
  System.out.println(new p019().run());
 }
 
 
 public String run() {
  int count = 0;
  for (int y = 1901; y <= 2000; y++) {
   for (int m = 1; m <= 12; m++) {
    if (dayOfWeek(y, m, 1) == 0)  // Sunday
     count++;
   }
  }
  return Integer.toString(count);
 }
 
 
 private static int dayOfWeek(int year, int month, int day) {
  long m = mod((long)month - 3, 4800);
  long y = mod(year + m / 12, 400);
  m %= 12;
  return (int)((y + y/4 - y/100 + (13 * m + 2) / 5 + day + 2) % 7);
 }
 
 
 private static long mod(long x, long y) {
  x %= y;
  if (y > 0 && x < 0 || y < 0 && x > 0)
   x += y;
  return x;
 }
 
}


No comments :

Post a Comment

Follow Me

If you like our content, feel free to follow me to stay updated.

Subscribe

Enter your email address:

We hate spam as much as you do.

Upload Material

Got an exam, project, tutorial video, exercise, solutions, unsolved problem, question, solution manual? We are open to any coding material. Why not upload?

Upload

Copyright © 2012 - 2014 Java Problems  --  About  --  Attribution  --  Privacy Policy  --  Terms of Use  --  Contact