Answer to Question #259261 in Algorithms for anju

Question #259261

What is space complexity? Discuss various factors affecting it. Write iterative and recursive algorithm of finding factorial of a given number and find its space complexity.


1
Expert's answer
2021-10-31T12:01:52-0400

The space complexity of an algorithm determines how much additional memory is required to execute this algorithm.

Additional memory may be required for additional variables used in the algorithm, and the size of these variables may be determined by the input data size (for example, the algorithm may require to create a copy of the input array). Also, when considering recursive algorithms, it is necessary to take into account the fact that with each call of a function, local copies of the variables (as well as its parameters) belonging to this function are created.


Iterative function:

function factorial(n)
set res = 1
for i from 2 to n do
  res = res * i
return res

The space complexity of this algorithm is O(1), as the size of additional variables (i and res) is independent of the input data (n)


Recursive function:

function factorial(n)
if n equal 1
  return 1
return n * factorial(n-1)

The space complexity of this algorithm is O(n), as the function factorial is called n times and each call creates a copy of the function's parameter n.



Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS