![](/img/trans.png)
[英]What should be the time complexity of the given function in terms of Big O?
[英]Is time complexity the only thing to consider when trying to compare two codes in terms of terms their speed?
最近,我編寫了一個代碼,用於在 C 中的“int”數據類型的范圍內查找數字的素因子。 當我把它展示給我的朋友時,他告訴我有更優化的方法,它們的時間復雜度為 O(sqrt(n))、O(log(n))。 當我運行時間復雜度為 O(sqrt(n)) 的代碼和我在 Dev C++ 上的代碼時,我看到兩個代碼所花費的總時間幾乎相同。 我的代碼的時間復雜度是多少?
#include <stdio.h>
int main(void)
{
int k = 2, n, m;
printf("enter a +ve integer greater than 1:- ");
scanf("%d", &n);
m = n;
do {
if (n % k == 0) {
n /= k;
printf("%d,", k);
}
if (n == 1)
break;
while (n % k != 0) {
if (k == 2)
k = 3;
else
k += 2;
}
} while (n % k == 0);
printf("prime factors of %d\n.", m);
return 0;
}
為了N 大而進行時間復雜度分析。 如果您還沒有感覺到效果,那么您的 N 還不夠大。 我將%d
s 更改為%lld
並將int
s 更改為long long int
並分解歐拉發現的梅森素數的平方,即 (2³¹-1)²。
結果:
% echo 4611686014132420609 | time ./a.out
enter a +ve integer greater than 1:- 2147483647,2147483647,prime factors of 4611686014132420609
../a.out 12.15s user 0.00s system 99% cpu 12.154 total
% echo 4611686014132420609 | time factor
4611686014132420609: 2147483647 2147483647
factor 0.00s user 0.00s system 87% cpu 0.001 total
即,即使使用 GCC 和 -O3 編譯,您的程序也需要至少 12000 倍的 CPU 功率來分解該數字,而不是factor
程序。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.