2

I was solving this problem on HackerRanked and found the following solution:

#include <iostream>
#include <vector>
using namespace std;
int main() {
    constexpr size_t BIG = 1u<<31;
    vector<bool> arr(BIG);
    size_t N,S,P,Q;
    cin >> N >> S >> P >> Q;
    size_t prev = S % BIG;
    arr.at(prev) = true;
    int count = 0;
    while (N--) {
        size_t curr = (prev*P+Q)% BIG;
        if(!arr.at(curr))
        {
            arr.at(curr) = true;
            ++count;
        }
        prev = curr;
    }
    cout << count;
}

I wanted to solve the same question using bitset, however it is not working... What am I doing wrong here?

#include <iostream>
#include <bitset>
using namespace std;
int main() {
    constexpr size_t BIG = 1u<<31;
    bitset<BIG> arr;
    size_t N, S, P, Q;
    cin >> N >> S >> P >> Q;
    size_t prev = S % BIG;
    arr.set(prev);
    while (N--) {
        size_t curr = (prev*P+Q)% BIG;
        arr.set(curr); prev = curr;
    }
    cout << arr.count();
}
Aamir
  • 1,974
  • 1
  • 14
  • 18
  • 4
    Good idea, but do you have enough bits on the stack for `bitset<2147483648> arr`? That's about 270 MB. – user4581301 Jan 13 '23 at 21:09
  • @user4581301 so bitset is on the stack? all I got to do is allocate it on the heap?? – Aboody Essam Jan 13 '23 at 21:11
  • In this case you just have to get it off the stack. See what happens with `static bitset arr;` – user4581301 Jan 13 '23 at 21:12
  • 1
    @user4581301 OMG it worked I spent days on that. Thanks a lot!! – Aboody Essam Jan 13 '23 at 21:13
  • Some reading on what `static` did: https://en.cppreference.com/w/cpp/language/storage_duration#Storage_duration – user4581301 Jan 13 '23 at 21:13
  • 3
    Here's a tool to help you quickly find mistakes like that in the future: https://godbolt.org/z/as81s9nWd The `-fsanitize=address,undefined` in the compiler options makes a program that hunts for common memory errors and program misbehaviours at runtime. – user4581301 Jan 13 '23 at 21:17

0 Answers0