Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the big o notation of following functions

I can't figure out the smallest upper barriers for those two functions.

I think ex1 has O(log_3(n)) and ex5 should have O(n!). But I'm not actually confident about this, since I haven't truly understood the subject yet.

public int ex1 ( int n ) {
    int r = 0 ;
    for ( int i = 1 ; i < n ; i++) {
        r += n ;
        n = n / 3 ;
    }
    return r ;
}
public static int ex5 ( int n ) {
    int r = 1 ;
    for ( int i = 0 ; i < n ; i ++) {
            r += ex5 ( n - 1 ) ;
    }
    return r ;
}
like image 580
L1me Avatar asked Dec 01 '13 22:12

L1me


People also ask

What is the big O complexity of the function?

Big O notation is used to describe the complexity of an algorithm when measuring its efficiency, which in this case means how well the algorithm scales with the size of the dataset.

How do you find Big O notation?

When we write Big O notation, we look for the fastest-growing term as the input gets larger and larger. We can simplify the equation by dropping constants and any non-dominant terms. For example, O(2N) becomes O(N), and O(N² + N + 1000) becomes O(N²). Binary Search is O(log N) which is less complex than Linear Search.

What is Big O notation types?

Big O Notation is a way to represent how long an algorithm will take to execute. It enables a software Engineer to determine how efficient different approaches to solving a problem are. Here are some common types of time complexities in Big O Notation.


1 Answers

The output values of ex5 correspond to sequence A000522 at oeis.org, which increases as a(n) = Sum_{k=0..n} n!/k! (or n! to a first approximation). Because of the horrible way this function is coded, this is equal to the function's time complexity.

A much better algorithm would be as follows:

public static int ex5 ( int n ) {
    return (n) ? 1 + n * ex5(n-1) : 1;
}

which is obviously O(n^2) O(n) (Sorry, it's late and I need sleep!).

EDIT: As everyone else is saying, the complexity of ex1 is O(log_3(n)), or simply O(log(n)), since log_3(n) = log(n)/log(3), and log(3) is a constant in any base.

like image 180
r3mainer Avatar answered Oct 05 '22 06:10

r3mainer