如何更有效地做到這一點?我認爲有一個標準的快速方法來做到這一點。但我無法找到。儘可能均勻地將間隔分爲n部分
這是用於在n個cpu內核之間劃分一些內存的工作。
輸出:
# Divide [0, 11) to 4 parts #
interval 0: [0, 3) with length: 3
interval 1: [3, 6) with length: 3
interval 2: [6, 9) with length: 3
interval 3: [9, 11) with length: 2
# Divide [0, 12) to 4 parts #
interval 0: [0, 3) with length: 3
interval 1: [3, 6) with length: 3
interval 2: [6, 9) with length: 3
interval 3: [9, 12) with length: 3
程序:
#include <iostream>
int part(int L, int n_parts, int part_id) {
int out = L/n_parts * part_id;
int r = L % n_parts;
if (part_id < r) {
out += part_id;
} else {
out += r;
}
return out;
}
void test(int L, int n_parts) {
std::cout << "# Divide [0, " << L << ") to "
<< n_parts << " parts #\n";
for (int i = 0; i < n_parts; ++i) {
int st = part(L, n_parts, i);
int en = part(L, n_parts, i + 1);
int len = en - st;
std::cout << "interval " << i <<": [" << st
<< ", " << en << ") "
<< "with length: " << len
<< "\n";
}
}
int main() {
test(11, 4);
test(12, 4);
}
到目前爲止,它使用1個區,1%,1次乘法,1點相比,和1除了(嗒嗒機器人在左右) 。
如果這個問題關閉,這意味着沒有更快的方法。 –
我認爲這個問題可能更適合[代碼評論](https://codereview.stackexchange.com/) – Isac
那個地方是墳墓。好長時間的節目...這樣簡單的事情不應該花那麼長時間。 –