【发布时间】:2018-02-21 16:03:22
【问题描述】:
Here is the link to algorithm without comments, to see better
function getLastFactor(n) {
var tempArr = [2, 3], max = Math.sqrt(n); /* (1 + 1)
it is despised
*/
for(var i = 5; i < max; i += 2) { /*
(sqrt(n) - 5) ---> ( 5 is despised )
*/
if(n%i) continue; /*
sqrt(n) - 5 operations
PD: Should I add this? or is it already included in the for, in (sqrt(n) - 5 above) ?
*/
if(check(tempArr, i)) continue; // How do I measure this? If I do not have security of the number?
tempArr.push(i); // 1 operation it is despised
}
return tempArr[tempArr.length - 1]; // 1 operation
}
function check(array, i) {
for(var j = 0, l = array.length; j < l; ++j) { // sqrt(n) operations
var cur = array[j]; // 1 operation
if(!(i%cur)) return true; // 1 operation
}
// O(3 * sqrt(n))
我不知道真正加起来是什么,我读过这并不重要,因为Big O 符号将其标准化,消除了次要顺序的条款。但我有很多疑问,比如我在代码本身中留下的一些疑问,还有:
1) 我应该计算依赖条件的操作吗? ,想象一下我有一个条件,如果你判断为真,会做一个循环来提高n次操作的效率,这个应该考虑到,因为它会造成很大的变化。
2)我认为这段代码的效率是
O (sqrt (n) * 3),这样对吗?
这个问题不是重复的,我通过网络阅读了很多,尤其是在这个社区,几乎所有的问题/答案都是基于理论的,几乎从未见过理论和实践的例子同时出现时间。
【问题讨论】:
标签: algorithm time-complexity big-o