本文介紹了有效地獲得給定數字的所有除數的處理方法,對大家解決問題具有一定的參考價值,需要的朋友們下面隨著小編來一起學習吧!
問題描述
根據這個帖子,我們可以通過以下代碼得到一個數的所有約數.
According to this post, we can get all divisors of a number through the following codes.
for (int i = 1; i <= num; ++i){
if (num % i == 0)
cout << i << endl;
}
例如24
的除數是1 2 3 4 6 8 12 24
.
搜索了一些相關的帖子,沒有找到好的解決辦法.有什么有效的方法可以做到這一點嗎?
After searching some related posts, I did not find any good solutions. Is there any efficient way to accomplish this?
我的解決方案:
- 通過這個解決方案.
- 獲取這些質因數的所有可能組合.
然而,這似乎不是一個好方法.
However, it doesn't seem to be a good one.
推薦答案
因素是成對的.1
and 24
, 2
and 12
, 3
and 8
、4
和 6
.
Factors are paired. 1
and 24
, 2
and 12
, 3
and 8
, 4
and 6
.
算法的改進可能是迭代到 num
的平方根,而不是一直到 num
,然后使用 計算配對因子num/i
.
An improvement of your algorithm could be to iterate to the square root of num
instead of all the way to num
, and then calculate the paired factors using num / i
.
這篇關于有效地獲得給定數字的所有除數的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!
【網站聲明】本站部分內容來源于互聯網,旨在幫助大家更快的解決問題,如果有圖片或者內容侵犯了您的權益,請聯系我們刪除處理,感謝您的支持!