Search code examples
calgorithmloopsnested-loops

Stepping away from loops


Im counting down how many Sunday 1st are there in the year interval lets say 2000/1/1 and 2020/5/2

I have made function for that which works fine , but the problem is i have nested loops inside which makes it quite slow .

int sundaycount = 0;
for (i = year1; i<year2; i++) { // years
    for (j = 0; j<12; j++) {
        if (isdate(i, j, 1)) {
            sundaycount++;
        }
    }
}
  • ofc there are conditions inside loops for right working , how could i step away from nested loops and make the iteration/code faster?

Solution

  • You should post the code for isdate(). We cannot verify your problem. I cannot believe 240 calls to mkdate() can qualify as slow.

    If you really want to use less computing power, compute the weekday for the 1st of January of the first year and iterate on the range of years, testing each month by adding the number of days modulo 7. Just be careful with leap years. This might consume a bit less CPU, but I doubt you can measure that.