Skip to content

Instantly share code, notes, and snippets.

@iamcrypticcoder
Created February 28, 2019 06:00
Show Gist options
  • Save iamcrypticcoder/bb2e69c36863490173905e7e4d51f296 to your computer and use it in GitHub Desktop.
Save iamcrypticcoder/bb2e69c36863490173905e7e4d51f296 to your computer and use it in GitHub Desktop.
Sigma calculation in efficient way
#include <iostream>
#include <vector>
#include <math.h>
using namespace std;
#define READ(x) freopen(x, "r", stdin)
#define WRITE(x) freopen(x, "w", stdout)
#define PB push_back
typedef unsigned long long ULL;
typedef vector<int> VI;
#define MAX_PRIME 10000000
#define MAX 10000000
uint bigPrime[MAX + 7];
uint t[MAX + 7];
ULL sigma[MAX + 7];
void preCal() {
t[1] = sigma[1] = 1;
int root = (uint)sqrt(MAX);
memset(bigPrime, 0, sizeof(bigPrime));
for (int i = 2; i <= MAX; ++i) {
if (bigPrime[i] == 0) {
bigPrime[i] = i;
if (i > root) continue;
for (int j = i*i; j <= MAX; j += i) {
bigPrime[j] = i;
}
}
}
for (int i = 2; i <= MAX; ++i) {
int p = bigPrime[i];
int a = 0;
int pa = p;
int tmp = i;
while (tmp % p == 0) {
tmp /= p;
a = a + 1;
pa = pa * p;
}
t[i] = (a + 1) * t[tmp];
sigma[i] = (pa - 1) / (p - 1) * sigma[tmp];
}
}
int main() {
WRITE("output.txt");
double cl = clock();
preCal();
for (int i = 1; i <= 30; ++i) {
printf("%d: %lu %llu\n", i, t[i], sigma[i]);
}
cl = clock() - cl;
fprintf(stderr, "Total Execution Time = %lf seconds\n", cl / CLOCKS_PER_SEC);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment