📅  最后修改于: 2023-12-03 15:26:05.356000             🧑  作者: Mango
UGC-NET CS 2017 November - III Problem 60 is a question from the Computer Science and Applications paper of the National Eligibility Test (NET) conducted by the University Grants Commission (UGC) in India. The problem is related to the concept of algorithms and their efficiency in terms of time and space complexity.
The problem statement for UGC-NET CS 2017 November - III Problem 60 is as follows:
Consider the following algorithm to find whether a given positive integer $n$ is a power of $2$ or not.
powersOfTwo(n):
if n == 1:
return true
while n % 2 == 0:
n = n / 2
return (n == 1)
What is the time complexity and space complexity of this algorithm?
The time complexity of an algorithm is a measure of the amount of time taken by an algorithm to solve a problem as a function of the size of the input.
In the given algorithm, the time complexity is determined by the number of times the while
loop is executed. The loop condition n % 2 == 0
checks whether $n$ is divisible by $2$, and the loop body divides $n$ by $2$. Thus, the loop is executed as long as $n$ is divisible by $2$, which means that the number of times it is executed is proportional to the number of times $n$ can be divided by $2$ before it becomes odd.
Since the algorithm divides $n$ by $2$ repeatedly until it becomes odd or $1$, the worst-case scenario is when $n$ is a power of $2$, in which case it will take $\log_2 n$ iterations of the loop to reduce $n$ to $1$. Therefore, the time complexity of the algorithm is $O(\log n)$.
The space complexity of an algorithm is a measure of the amount of memory used by an algorithm to solve a problem as a function of the size of the input.
In the given algorithm, the only variable used is $n$, which has a constant size of $\log_2 n$ bits, regardless of the value of $n$. Therefore, the space complexity of the algorithm is $O(\log n)$.
UGC-NET CS 2017 November - III Problem 60 is a question that tests the understanding of time and space complexity of algorithms. The given algorithm is used to check whether a positive integer is a power of $2$ or not, and its time and space complexity are analyzed in terms of the size of the input. The time complexity is $O(\log n)$, and the space complexity is $O(\log n)$, where $n$ is the input value.