[英]any suggestions to improve and bypass timeout error test with this prime finder function?
我應該創建一個函數來為給定的數字找到最接近的下一個素數,我的意思是即使算法寫得不好而且很慢(可能是最慢的),但它完成任務,問題是應該評估我的東西的程序以超時錯誤拒絕它,他一次給了它一堆數字,他希望它們在 10 秒內全部解決,所以問題是你可能建議有什么改進可以讓我的窮人快進折磨? ( for
是不允許的)
int is_prime(int nb)
{
int i;
/* if negative terminate */
if (nb <= 1)
return (0);
/* start from first prime */
i = 2;
/* primes equals zero only when divisible by 1 and theme-selves */
while (nb % i != 0)
i++;
/* if i divides nb, we see if i is the nb we looking for */
if (i == nb)
return (1);
else
return (0);
}
int find_next_prime(int nb)
{
int i;
i = 0;
/*keep looking for primes one by one */
while (!is_prime(nb + i))
i++;
return (nb + i);
}
最好的簡單的速度提升是檢查除數高達平方根n
而不是所有的除數高達n
。 這使算法從 O(nb) 到 O(sqrt(nb))。
考慮is_prime(2147483647)
。 OP 的方法需要大約 2147483647 次迭代。 測試到大約平方根 46341,大約快 46,000 倍。
// while (nb % i != 0) i++;
// if (i == nb) return (1);
// else return (0);
// While the divisor <= quotient (or until the square root is reached)
while (i <= nb/i) {
if (nb%i == 0) return 1;
i++;
}
return 0;
避免i*i <= nb
測試,因為i*i
可能會溢出。
避免sqrt(nb)
因為它涉及大量浮點/ int
問題。
注意:好的編譯器會看到附近的nb/i; nb%i
nb/i; nb%i
並計算它們兩者的時間成本。
許多其他改進是可能的,但希望專注於一個具有重大影響的簡單改進。 當想要提高速度時,專注於降低復雜度O() 的順序而不是線性改進。 過早優化真的是萬惡之源嗎?
你錯過了兩個最常見的提高速度的技巧。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.