How to calculate the year from the number of days?

1

Without using any library, and ignoring small 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 starting year is 0 (meaning you need 366 days to arrive in year 1)

Briefly: Multiple years of 4 that are not multiple of 100 are bisexual, multiple years of 400 are always bisexual: (ano % 4 == 0 && ano % 100 == 0) || (ano % 400 == 0)

What I tried was the following:

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 not implement the differences of 100 and 400

    
asked by anonymous 04.05.2017 / 15:42

1 answer

0
int ano = 0

while dias > 0 {

    if ano == bissexto then 
        dias = dias-366
    else 
        dias = dias-365

    ano++
} 

return ano 
    
04.05.2017 / 23:10