How to calculate the year from the number of days?

Asked

Viewed 425 times

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.

1 answer

0


int ano = 0

while dias > 0 {

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

    ano++
} 

return ano 
  • Can you explain the code?

  • This code doesn’t make much sense, I’m sorry, but I don’t understand how to apply it to the problem

  • After testing here I understood, just by the condition in the place there bisexto ... but do this does not get heavy ? let’s say in a query (sql) return loop with 2000 years up ?

  • I did it on my phone and the editing is not very practical, so I put the algorithm and not an executable code.

  • 1

    It is to be developed in SQL?

Browser other questions tagged

You are not signed in. Login or sign up in order to post.