[英]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.