0
#include <stdio.h>

int main()
{
    int ix;
    unsigned hits = 0;
    for (ix=0; ix < 128; ix++)
    {   
        if (ix % 4 == 0)
            continue;   

        hits++;
    }
    printf("%u hits\n", hits);
    return;
}

This isn't a programming question, I have no code like this. But I'm interested in the mathematical way to handle such a problem. The printf returns "96 hits" My question is, is there a formula for calculating 'hits' without the loop?

Level 42
  • 400
  • 2
  • 7

1 Answers1

1

This piece:

if (ix % 4 == 0)
    continue;   

basically means "skip every fourth iteration". Which means that it's the same as reducing the mount of iterations with 25%. So in this case, since the operation hits++ does not depend on the value if ix at all, the whole thing is the same as:

unsigned hits = 0;
for (ix=0; ix < 128 * 3/4; ix++)
{   
    hits++;
}

And since the only operation is an increment, you can change everything to just

hits = 128*3/4;
klutt
  • 30,332
  • 17
  • 55
  • 95