Last active
September 28, 2015 17:23
-
-
Save oten/6df5addccf629784a551 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
#include <sstream> | |
#include <omp.h> | |
using namespace std; | |
void sum(char* output, const long unsigned int d, const long unsigned int n) { | |
long unsigned int digits[d + 11]; | |
int num_threads; | |
#pragma omp parallel | |
num_threads = omp_get_num_threads(); | |
long unsigned int t_digits[num_threads][d + 11]; | |
for(int i = 0; i < num_threads; i++ ) fill_n(t_digits[i], d + 11, 0); | |
fill_n(digits, d + 11, 0); | |
#pragma omp parallel for | |
for (long unsigned int i = 1; i <= n; ++i) { | |
long unsigned int remainder = 1; | |
int tid = omp_get_thread_num(); | |
for (long unsigned int digit = 0; digit < d + 11 && remainder; ++digit) { | |
long unsigned int div = remainder / i; | |
long unsigned int mod = remainder % i; | |
t_digits[tid][digit] += div; | |
remainder = mod * 10; | |
} | |
} | |
for (long unsigned int digit = 0; digit < d + 11; ++digit) { | |
for(int i = 0; i < num_threads; i++) { | |
digits[digit] += t_digits[i][digit]; | |
} | |
} | |
for (long unsigned int i = d + 11 - 1; i > 0; --i) { | |
digits[i - 1] += digits[i] / 10; | |
digits[i] %= 10; | |
} | |
if (digits[d + 1] >= 5) { | |
++digits[d]; | |
} | |
for (long unsigned int i = d; i > 0; --i) { | |
digits[i - 1] += digits[i] / 10; | |
digits[i] %= 10; | |
} | |
stringstream stringstreamA; | |
stringstreamA << digits[0] << ","; | |
for (long unsigned int i = 1; i <= d; ++i) { | |
stringstreamA << digits[i]; | |
} | |
stringstreamA << '\0'; | |
string stringA = stringstreamA.str(); | |
stringA.copy(output, stringA.size()); | |
} | |
int main() { | |
long unsigned int d, n; | |
cin >> d >> n; | |
char output[d + 10]; // extra precision due to possible error | |
sum(output, d, n); | |
cout << output; | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment