Lemma

Let .

Du’s Second Multiplication Sieve is an algorithm that computes and for multiplicative functions and , if , , , and are given, in time and space.

Algorithm

Lemma

  1. For each in , find .

  2. Use the results from Step 1 to find .

  3. Use the results from Step 2 to find .

  4. For each in , apply the lemma to find .

This algorithm solves the problem in time and space.

std::unordered_map<int, int> du(int n, const std::unordered_map<int, int> &sf, const std::unordered_map<int, int> &sg) {
	int m = std::pow(n, .67);
 
	std::vector<int> h(m);
	h[1] = 1;
	for (int i = 2; i < m; i++) {
		if (pk[i] == i) {
			h[i] = 0;
			for (int j = i; j; j /= pf[i]) {
				h[i] += (sf.at(j) - (j > 1 ? sf.at(j - 1) : 0)) * (sg.at(i / j) - (i > j ? sg.at(i / j - 1) : 0));
			}
		} else {
			h[i] = h[i / pk[i]] * h[pk[i]];
		}
	}
 
	std::unordered_map<int, int> sh;
	sh[1] = h[1];
	for (int i = 2; i < m; i++) {
		sh[i] = sh[i - 1] + h[i];
	}
	for (int i = n / m; i > 0; i--) {
		sh[n / i] = 0;
		for (int j = 1; j <= n / i; j = n / i / (n / i / j) + 1) {
			sh[n / i] += (sg.at(n / i / (n / i / j)) - (j > 1 ? sg.at(j - 1) : 0)) * sf.at(n / i / j);
		}
	}
	return sh;
}