Skip to content

Instantly share code, notes, and snippets.

@chris3k
Created January 23, 2024 13:29
Show Gist options
  • Save chris3k/fc159d3eee874f323456a27055189820 to your computer and use it in GitHub Desktop.
Save chris3k/fc159d3eee874f323456a27055189820 to your computer and use it in GitHub Desktop.
get every number in [0, n) range only once, in pseudo-random order
#include <iostream>
#include <numeric>
//
// `ax + b mod n`, where `[0,n)`
// `a` must be a coprime with `n`,
// `gcd(a, n) = 1`
// `a=1` is bad for obvious reasons, so we gonna pick `a` from `[n/2, n)`.
//
int main() {
const int b = 7;
const int n = 120;
const int a = []() {
for (int p = n / 2 + b; p < n; p++) {
if (std::gcd(p, n) == 1) {
return p;
}
}
return -1;
}();
if (a == -1) {
return -1;
}
for (int i = 0; i < n; i++) {
int v = (a * i + b) % n;
std::cout << v << '\n';
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment