We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
Approach: figure out what day is January 1st for the start year.
This can be done mathematically by adding 365 starting from year 1900, plus the number of leap years before the end year.
From January 1st, we go to the first of each months, counting Sundays. We need to do it no more than 12 * 1000 times.
C++
intdays[13]={0,31,28,31,30,31,30,31,31,30,31,30,31};intjan1st(longlongy){// Monday is zero.longlongleaps=(y-1901)/4-(y-1901)/100+(y-1601)/400;return((y-1900)*365+leaps)%7;}longlongcountSundays(longlongy1,intm1,longlongy2,intm2){intcur=jan1st(y1),cnt=0;for(longlongy=y1;y<=y2;++y){boolisLeap=y%100==0?y%400==0:y%4==0;for(intm=1;m<=(y==y2?m2:12);++m){if(y1<y||m>=m1)cnt+=cur==6;cur=(cur+days[m]+(isLeap&&m==2))%7;}}returncnt;}intmain(){intt,m1,d1,m2,d2;longlongy1,y2;cin>>t;while(t--){cin>>y1>>m1>>d1;cin>>y2>>m2>>d2;cout<<countSundays(y1,m1+(d1>1),y2,m2)<<endl;}return0;}
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
Project Euler #19: Counting Sundays
You are viewing a single comment's thread. Return to all comments →
Approach: figure out what day is January 1st for the start year.
This can be done mathematically by adding 365 starting from year 1900, plus the number of leap years before the end year.
From January 1st, we go to the first of each months, counting Sundays. We need to do it no more than 12 * 1000 times.
C++