1
Without using any library, and ignoring little scientific facts about the rotation of the earth. The function receives the number of days and must determine how many years have passed judging the following :
- Multiple years of 4 have 366 days
- Multiple years of 100 have 365 days
- Multiple years of 400 have 366 days
- The initial year is 0 (i.e., it takes 366 days to arrive in year 1)
Briefly : Multiples of years of 4 that are not multiples of 100 are bisexts, multiples of years of 400 are always bisexts : (ano % 4 == 0 && ano % 100 == 0) || (ano % 400 == 0)
What I tried was this :
int ano(long dias) {
long anos = dias / 1461L * 4L;
long bisextos = dias % 1461L;
if (bisextos < 366) {
return (int) (anos);
} else if (bisextos < 731) {
return (int) (anos + 1);
} else if (bisextos < 1096) {
return (int) (anos + 2);
} else {
return (int) (anos + 3);
}
}
And the reverse operation :
int ano(long anos) {
long dias = 0L;
long mod = anos % 4L;
if (anos > 0) {
dias += ((anos - mod) * 36525L) / 100L;
if (mod > 0) {
dias += 366L + (mod - 1L) * 365L;
}
}
return dias;
}
It’s working, but I can’t implement the differences of 100 and 400
Now it makes sense, but I think it would be good if you tried to make the question explicit. 'Cause even though I read all of it, I ended up taking it to the "real" side of the thing, it can happen to more people.
– Jéf Bueno