Replace for loop with formula
        Posted  
        
            by hamax
        on Stack Overflow
        
        See other posts from Stack Overflow
        
            or by hamax
        
        
        
        Published on 2010-04-09T18:26:56Z
        Indexed on 
            2010/04/09
            18:53 UTC
        
        
        Read the original article
        Hit count: 181
        
I have this loop that runs in O(end - start) and I would like to replace it with something O(1).
If "width" wouldn't be decreasing, it would be pretty simple.
for (int i = start; i <= end; i++, width--)
    if (i % 3 > 0) // 1 or 2, but not 0
        z += width;
start, end and width have positive values
© Stack Overflow or respective owner