[英]Is time complexity the only thing to consider when trying to compare two codes in terms of terms their speed?
Recently i wrote a code for finding primefactors of a number within the limits of "int" datatype in C.最近,我编写了一个代码,用于在 C 中的“int”数据类型的范围内查找数字的素因子。 When i showed it to my friend he told that there are more optimised ways which have time complexities of O(sqrt(n)), O(log(n)).
当我把它展示给我的朋友时,他告诉我有更优化的方法,它们的时间复杂度为 O(sqrt(n))、O(log(n))。 When I ran the code having time complexity O(sqrt(n)) and my code on Dev C++ i saw that the total time taken by both the codes was nearly the same.
当我运行时间复杂度为 O(sqrt(n)) 的代码和我在 Dev C++ 上的代码时,我看到两个代码所花费的总时间几乎相同。 What is the time complexity of my code?
我的代码的时间复杂度是多少?
#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;
}
The time-complexity analysis is made for the sake of large N .为了N 大而进行时间复杂度分析。 If you do not feel the effect yet, your N is not large enough.
如果您还没有感觉到效果,那么您的 N 还不够大。 I changed the
%d
s to %lld
and int
s to long long int
and factored the square of the Mersenne prime that Euler found, ie (2³¹-1)².我将
%d
s 更改为%lld
并将int
s 更改为long long int
并分解欧拉发现的梅森素数的平方,即 (2³¹-1)²。
Results:结果:
% 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
Ie even when compiled with GCC and -O3, your program required at least 12000 times as much CPU power to factor the number than the factor
program.即,即使使用 GCC 和 -O3 编译,您的程序也需要至少 12000 倍的 CPU 功率来分解该数字,而不是
factor
程序。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.