简体   繁体   English

big-O表示法中以下函数的时间复杂度是多少?

[英]What is the time complexity of the following function in big-O notation?

I'm working on understanding big O and I have run into a tricky problem. 我正在努力理解大O,但遇到了一个棘手的问题。

When I look at this code, I immediately think O(n) just by looking at the for loop but the line 当我看这段代码时,我立即通过查看for循环就认为O(n)

result = result * k

makes me think it is something different. 让我觉得这是不同的。

if power(int n, int k)
{
    int result = n
    for (int i = 1; i < n; i++){
        result = result * k
    }
}

Just looking for some clear explanation on why I may or may not be wrong 只是寻找一些明确的解释来说明为什么我可能会错,也可能不会错

This is not a tricky problem unless you're using a language like C++ that permits operator overloading and the operator*() method of types of k or result is overloaded, or else there is a standalone (free) overloaded operator method defined with those types as its arguments. 除非您使用的语言像C ++这样允许操作符重载,并且kresult类型的operator *()方法被重载,否则否则这不是一个棘手的问题,否则将使用这些定义的独立(免费)重载操作符方法类型作为其参数。 I'm assuming this is not the case, so: 我假设情况并非如此,所以:

Your loop is of order O(n). 您的循环的阶数为O(n)。 Within that loop, what do you do? 在该循环中,您要做什么? Do you do another loop? 您是否还要进行其他循环? Or call a method that does so? 或调用这样做的方法? No. Is your system's multiply operator complexity based on the size of its operands? 否。系统的乘法运算符复杂度是否基于其操作数的大小? Perhaps technically yes, since a 32-bit multiply will be faster on a 32-bit core than a 64-bit multiply, but that's based on the types of the operands, not on the operands' values. 从技术上来说也许是肯定的,因为32位乘法在32位内核上比64位乘法要快,但这是基于操作数的类型 ,而不是基于操作数的值。 Multiply operations are normally of order O(1). 乘法运算通常为O(1)阶。

So the overall complexity is O(n*1), or just O(n). 因此,总体复杂度为O(n * 1)或仅为O(n)。

The only way this is anything other than O(n) is if the multiply operator is overloaded, and implemented in a naive way; 除O(n)之外,这是唯一的方法是乘法运算符被重载并以幼稚的方式实现。 eg if it does the integer multiplication by iterating k times and adding result to itself k times. 例如,是否通过迭代k次并将result相加k次来进行整数乘法。 In that case , the overall complexity would be O(n 2 ). 在这种情况下 ,总体复杂度将为O(n 2 )。

But in any normal case the complexity is just O(n). 但是在任何正常情况下,复杂度仅为O(n)。

This is only a statement, this is not about group of statements that iterations not dependent on n. 这只是一个语句,与迭代不依赖于n的语句组无关。 So we know about this result = result * k this is in O (1) in any case its time complexity can't change. 因此,我们知道结果=结果* k在任何情况下都不会改变的O(1)中。 time complexity of your code is O (n) not more than O (n) 您的代码的时间复杂度为O(n)不大于O(n)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM