• + 0 comments

    I think like most people, I simply started to program, leading me to a simple interpretation of the pseudo-code that used a set to track distinct integers; of course that implementation didn't pass any of the timed test cases.

    In the end, this problem is not about c++, but an understanding of algorithms. After research, I stumbled across the idea of cycle detection https://en.wikipedia.org/wiki/Cycle_detection, and tried out the first algorithm listed.

    I know many people don't like it when code is shared since it kind of defeats the “test” notion, but when I get stuck, I personally am thankful for those who post so I can treat the question as a learning exercise (I spent more time researching this than coding this one):

    #include <cmath>
    #include <cstdio>
    #include <iostream>
    using namespace std;
    
    const unsigned bit_mask = ((1U << 31) - 1);
    
    inline unsigned mask(unsigned num) {
        return num & bit_mask;
    }
    
    inline unsigned next_value(unsigned value, unsigned P, unsigned Q) {
        return mask(value * P + Q);
    }
    
    int main() {
        // Get the 4 input integers as unsigned ints
        unsigned N, S, P, Q; cin >> N >> S >> P >> Q;
        
        // Used Floyd's tortoise and hare cycle-finding algorithm:
        //  https://en.wikipedia.org/wiki/Cycle_detection
        unsigned tort = mask(S);
        unsigned hare = tort;
        unsigned cycle = 1;
        
        // Calculate the length of a cycle (if one exists) or stop at N
        for (unsigned i = 1; i < N; i++) {
            tort = next_value(tort, P, Q);
            hare = next_value(next_value(hare, P, Q), P, Q);
            cycle++;
            
            if (tort == hare) break;
        }
        
        cout << cycle;
        
        return 0;
    }
    

    This isn’t a perfect solution - I know I have personal coding idiosyncrasies, and it doesn’t take into account edge cases such as N == 0 or P == 0 - but it does streamline Floyd’s solution with the knowledge of the limit N and does so in under 40 lines of code.

    Hopefully this inspires others to go back to the research when they get the “Time limit exceeded” on their test case(s).