Project Euler #19: Counting Sundays

  • + 0 comments

    My code failed for test cases 2 3 4 5 but i didnt really what's wrong with my code Can someone help me, my code is written in C++

    #include <bits/stdc++.h>
    
    using namespace std;
    
    int days[13] = {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
    
    int isLeapYear(long long y){
        if(y%4==0 && y%100!=0) return 1;
        if(y%400 == 0) return 1;
        else return 0;
    }
    
    int first(long long y, int m){
        long long LeapYears = (y - 1901)/4 - (y - 1901)/100 + (y - 1601)/400;
        long long NumOfDays = (y - 1900)*365 + LeapYears;
        for(int i = 1; i < m; i++){
            if(i == 2) NumOfDays += days[2] + isLeapYear(y);
            else NumOfDays += days[i];
        }
        return NumOfDays%7;
    }
    
    long long CountingSundays(long long y1, long long y2, int m1, int m2){
        long long cnt = 0;
        int isSunday = first(y1, m1);
        for(int m = m1; m <= 12; m++){
            if(isSunday == 6) cnt++;
            isSunday += days[m];
            if(m==2) isSunday += isLeapYear(y1);
            isSunday %= 7;
        }
    
        for(long long y = y1+1; y < y2; y++){
            for(int m = 1; m <= 12; m++){
                if(isSunday == 6) cnt++;
                isSunday += days[m];
                if(m==2) isSunday += isLeapYear(y);
                isSunday %= 7;
            }
        }
    
        for(int m = 1; m < m2; m++){
            if(isSunday == 6) cnt++;
            isSunday += days[m];
            if(m==2) isSunday += isLeapYear(y2);
            isSunday %= 7;
        }
        return cnt;
    }
    
    int main(){
        int t; cin >> t;
        while(t--){
            long long y1, y2; int m1, m2, d1, d2;
            cin >> y1 >> m1 >> d1 >> y2 >> m2 >> d2;
            if(d1 > 1) m1++;
            cout << CountingSundays(y1,y2,m1,m2) << endl;
        }
    }