I am given a question to write a method with a time complexity of O(4^n).
I have came out with this algorithm:
public void test(int n){
for(int i = 0; i<n;i++){
test(4*i);
}
}
Is this be considered to be running on O(4^n)?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
You were quite close with your program. The correct function would go like this:
Run this piece of code to check:
It will print
The run count is off by one, but the big-O complexity is satisfied.
The reasoning as to why it is O(4n) is probably quite obvious once you see it, but a little explanation cannot hurt. The function is best imagined to be solving a complex problem by divide-and-conquer. It reduces an n-sized problem to four instances of an (n-1)-sized problem, recursing until the subproblem is trivial (size 0). A problem of size 1 is therefore solved in 1+4 steps (entry-point call + 4 trivial subproblems); a problem of size 2 in 1 + 4*(1 + 4) = 21 steps, and so on.