埃氏筛法、gcd和lcm、快速幂、乘法逆元

埃氏筛法:

https://www.starrycoding.com/problem/43

// Problem: ${json.name}
// Contest: ${json.group}
// URL: ${json.url}
// Memory Limit: ${json.memoryLimit} MB
// Time Limit: ${json.timeLimit} ms
// More thought is needed

#include <bits/stdc++.h>
#define endl '\n'
#define int long long
using namespace std;
const int N = 2e6 + 9;
void solve() {
  int n;
  cin >> n;
  bitset<N> vis;
  for (int i = 2; i <= n; i++) {
    if (!vis[i])
      for (int j = i * 2; j <= n; j += i) vis[j] = 1;
  }
  for (int i = 2; i <= n; i++)
    if (!vis[i]) cout << i << " ";
}

signed main() {
  ios::sync_with_stdio(false), cin.tie(nullptr), cout.tie(nullptr);
  solve();
  return 0;
}

gcd和lcm:

https://www.starrycoding.com/problem/65

// Problem: ${json.name}
// Contest: ${json.group}
// URL: ${json.url}
// Memory Limit: ${json.memoryLimit} MB
// Time Limit: ${json.timeLimit} ms
// More thought is needed

#include <bits/stdc++.h>
#define endl '\n'
#define int long long
using namespace std;
int gcd(int a, int b) { return b == 0 ? a : gcd(b, a % b); }
int lcm(int a, int b) { return a * (b / gcd(a, b)); }
void solve() {
  int a, b;
  cin >> a >> b;
  cout << gcd(a, b) << " " << lcm(a, b) << endl;
}

signed main() {
  ios::sync_with_stdio(false), cin.tie(nullptr), cout.tie(nullptr);
  int _;
  cin >> _;
  while (_--) solve();
  return 0;
}

快速幂:

用二进制想很简单:

https://www.starrycoding.com/problem/66

// Problem: ${json.name}
// Contest: ${json.group}
// URL: ${json.url}
// Memory Limit: ${json.memoryLimit} MB
// Time Limit: ${json.timeLimit} ms
// More thought is needed

#include <bits/stdc++.h>
#define endl '\n'
#define int long long
using namespace std;

int fastabs(int a, int b, int c) {
  int res = 1;
  while (b) {
    if (b & 1) res = res * a % c;
    a = a * a % c;
    b >>= 1;
  }
  return res;
}

void solve() {
  int a, b, c;
  cin >> a >> b >> c;
  cout << fastabs(a, b, c) << endl;
}

signed main() {
  ios::sync_with_stdio(false), cin.tie(nullptr), cout.tie(nullptr);
  int _;
  cin >> _;
  while (_--) solve();
  return 0;
}

乘法逆元:

https://www.starrycoding.com/problem/44

// Problem: ${json.name}
// Contest: ${json.group}
// URL: ${json.url}
// Memory Limit: ${json.memoryLimit} MB
// Time Limit: ${json.timeLimit} ms
// More thought is needed

#include <bits/stdc++.h>
#define endl '\n'
#define int long long
using namespace std;
const int N = 998244353;

int fastabs(int a, int b) {
  int res = 1;
  while (b) {
    if (b & 1) res = res * a % N;
    a = a * a % N;
    b >>= 1;
  }
  return res;
}

int MOX(int a, int b, int c, int x) {
  return ((a * x % N + b) % N * fastabs(c * x % N, N - 2) % N) % N;
}

void solve() {
  int a, b, c, q;
  cin >> a >> b >> c >> q;
  for (int i = 1; i <= q; i++) {
    int x;
    cin >> x;
    cout << MOX(a, b, c, x) << endl;
  }
}

signed main() {
  ios::sync_with_stdio(false), cin.tie(nullptr), cout.tie(nullptr);
  int _;
  cin >> _;
  while (_--) solve();
  return 0;
}

发表评论

您的邮箱地址不会被公开。 必填项已用 * 标注

滚动至顶部