我想存儲所有數字從1到10^6的所有除數。但是這似乎太慢了。這是我的代碼的預處理()函數:最有效的方法來找到兩個數字的公約數達10^6
for(int i=1; i<=1000000; i++)
{
for(int j=1; j<=i/2; j++)
{
if(i%j==0)
divi[i][j] = true;
}
}
我用這樣的地圖容器:
map <int, bool> divi[1000010];
然後我試圖找到兩個給定數字的公約數。
preprocess();
int T, A, B;
cin >> T;
while(T--)
{
cin >> A >> B;
int common = 0;
for(it = divi[A].begin(); it!=divi[A].end(); it++)
{
if(divi[B][it->first]==true)
common++;
}
cout << common << endl;
現在應該如何使它足夠快?
看看[Euclidean_algorithm](https://en.wikipedia.org/wiki/Euclidean_algorithm) – Jarod42
請注意'divi [B] [it-> first] == true'會創建一個新的地圖條目,如果不存在的話。這變得非常昂貴,特別是對於素數。 – molbdnilo
順便說一句,'std :: map'可能會被替換爲'std :: set '。 –
Jarod42