问题 19 项目 Euler Counting Sundays
Problem 19 project Euler Counting Sundays
这是我 Project Euler #19 的代码。问题的答案是 171,但我的代码生成了 172。请任何人找出下面代码中的问题。
#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 ;
}
如果不是闰年,你需要else statement
分配leapFlag = 0
:
if ( (i%4==0 && i%100!=0) || (i%100==0 && i%400==0) )
leapFlag = 1;
else
leapFlag = 0;
这是我 Project Euler #19 的代码。问题的答案是 171,但我的代码生成了 172。请任何人找出下面代码中的问题。
#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 ;
}
如果不是闰年,你需要else statement
分配leapFlag = 0
:
if ( (i%4==0 && i%100!=0) || (i%100==0 && i%400==0) )
leapFlag = 1;
else
leapFlag = 0;