Time complexity of Recursive Algorithms

Source: Internet
Author: User

Introduction: the solution of time complexity is explained here by examples, which can be understood by readers. All of the following cases are written in Python!

Case 1: Calculate the Npower of

The Code is as follows:

Def exp1 (A, n ):

If n = 1:

Return

Else:

Return a * exp2 (A, n-1)

Analysis: 1. The problem scale is N; 2. When the scale is 1, it ends; 3. Suppose T (n) represents the number of steps required for the problem where the scale is N;

Solution:

T (n) = 3 + T (n-1) // Note: 3 represents the number of operations in a loop, and the comparison of IF is "= ", the second operation is the "-" in n-1 in recursion, and the third operation is the "*" in a * exp1 (A, n-1). Each time the scale is reduced, the above three operations are performed.

Decomposition: T (n) = 3 + 3 + T (n-2)

= 3 + 3 + 3 + T (n-3)

......

= 3 * k + T (n-k)

When the scale is 1, the returned result is n-k = 1-"K = n-1, bringing K into T (N)

T (n) = 3 (n-1) + T (1) = 3n-3 + 2 = 3n-1 // Note: When T (1) is 1, two operations are performed.

To sum up, the time complexity of the above procedures is: O (n)

This article from the "heaven reward diligence" blog, please be sure to keep this source http://737110312.blog.51cto.com/2927801/1441502

Time complexity of Recursive Algorithms

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.