c++mathadhoc

Problem 19 project Euler Counting Sundays


This is my code for Project Euler #19. The answer for the problem is 171 but my code is producing 172. Please can anyone figure out the problem in the code below.

#include <bits/stdc++.h>
using namespace std ;
typedef long long LL ;
int ordYear[12] = {31,28,31,30,31,30,31,31,30,31,30,31} ;
int leapYear[12] = {31,29,31,30,31,30,31,31,30,31,30,31} ;

int main(){
    int leapFlag = 0 ;
    LL ans = 0 ;
    int dayonfirst = 2 ; // since it was tuesday on 1 Jan 1901
    for (int i=1901 ; i<=2000 ; i++){
        if ( (i%4==0 && i%100!=0) || (i%100==0 && i%400==0) )
            leapFlag = 1 ;
        for (int i=0 ; i<12 ; i++){
            int oddDays ;
            if (leapFlag == 1)
                oddDays = leapYear[i]%7 ;
            else
                oddDays = ordYear[i]%7 ;
            dayonfirst += oddDays  ;
            if(dayonfirst == 7)
                ans++ ;
            else if (dayonfirst > 7)
                dayonfirst = dayonfirst%7 ;
        }
    }
    cout << ans << endl ;
    return 0 ;
}

Solution

  • You need else statement to assign leapFlag = 0 when it not a leap year:

    if ( (i%4==0 && i%100!=0) || (i%100==0 && i%400==0) )
        leapFlag = 1; 
    else 
        leapFlag = 0;