Skip to content

Instantly share code, notes, and snippets.

@lmduc
Created February 21, 2019 16:04
Show Gist options
  • Save lmduc/da7edfe96f988a0d3aafa1ad78d18993 to your computer and use it in GitHub Desktop.
Save lmduc/da7edfe96f988a0d3aafa1ad78d18993 to your computer and use it in GitHub Desktop.
Concurrent sum square C++
#include <bits/stdc++.h>
#include <thread>
#include <atomic>

using namespace std;

int MODULO = 123456789;

#define ll long long
#define FOR(i, s, d) for(int i = s; i <= d; ++i)

atomic<int> result(0);

ll pow(ll base, int exp) {
  if (exp == 1) return base;
  if (exp%2) return (base*pow(base, exp-1))%MODULO;
  ll t = pow(base, exp/2);
  return (t*t)%MODULO;
}

void sum(int i) {
  result = (result + pow(i, i))%MODULO;
}

int main() {
  int n; cin >> n;
  vector<thread> ts;
  FOR(i, 1, n) ts.push_back(thread(&sum, i));
  for (thread& t : ts) t.join();
  cout << result << endl;
  return 0;
}

Time complexity: O(n*log(n)/cores) Space complexity: O(n)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment