views:

1115

answers:

11
+19  Q: 

Example of O(n!)?

What is an example (in code) of a O(n!) function? It should take appropriate number of operations to run in reference to n; that is, I'm asking about time complexity.

+19  A: 

One classic example is the traveling salesman problem through brute-force search.

If there are N cities, the brute force method will try each and every permutation of these N cities to find which one is cheapest. Now the number of permutations with N cities is N! making it's complexity factorial (O(N!)).

codaddict
i need an example in codes? couldnt find in the net.
Derek Long
@Downvoter: Care to explain?
codaddict
I didn't DV, but perhaps it's because it has no sample code, and the big-o notation is not provided...
aioobe
@aioobe: since the question is "What's an O(n!) problem" and the answer is "here's one", I wouldn't think you have to say O(n!) explicitly..
Claudiu
Ah, yes. I didn't see that the OP asked for a specific complexity... I agree :)
aioobe
+24  A: 

There you go. This is probably the most trivial example of a function that runs in O(n!) time (where n is the argument to the function):

void nFac(int n) {
  for(int i=0; i<n; i++) {
    nFac(n-1);
  }
}
sepp2k
Looks like O(n²) to me...
aioobe
@aioobe: That's what I thought at first glance too. But it's N!
Armen Tsirunyan
Ah! I see it now :-) thanks!
aioobe
Given that this is a one-for-one calculation of n!, this is *the very definition* of O(n!) order of growth.
Adam Robinson
isnt this O(N)?
Derek Long
You know of any O(N!) time complexity codes? I am pulling my hair right now !!! sad face :(
Derek Long
On a second thought, will the recursive method nFac affect the time complexity of this algorithm?
Derek Long
@Derek: It's definitely `O(n!)` (and more importantly `Θ(n!)`). And yes, the time complexity of a function called in a loop affects the time complexity of the loop. If the loop is executed `n` times and the function in the loop executes `(n-1)!` steps, then a total of `n * (n-1)! = n!` steps will be performed. Which is exactly how you proof that this function's time complexity is in `Θ(n!)`.
sepp2k
@Derek Long the loop is O(n), since it is called recursively with (n-1) you get n * (n-1)*(n-2)*...*1 = n! so the function is O(n!).
josefx
+3  A: 

the simplest example :)

pseudocode:

input N
calculate N! and store the value in a vaiable NFac - this operation is o(N)
loop from 1 to NFac and output the letter 'z' - this is O(N!)

there you go :)

As a real example - what about generating all the permutations of a set of items?

Armen Tsirunyan
+4  A: 

Finding the determinant with expansion by minors.

Very good explanation here.

# include <cppad/cppad.hpp>
# include <cppad/speed/det_by_minor.hpp>

bool det_by_minor()
{   bool ok = true;

    // dimension of the matrix
    size_t n = 3;

    // construct the determinat object
    CppAD::det_by_minor<double> Det(n);

    double  a[] = {
        1., 2., 3.,  // a[0] a[1] a[2]
        3., 2., 1.,  // a[3] a[4] a[5]
        2., 1., 2.   // a[6] a[7] a[8]
    };
    CPPAD_TEST_VECTOR<double> A(9);
    size_t i;
    for(i = 0; i < 9; i++)
        A[i] = a[i];


    // evaluate the determinant
    double det = Det(A);

    double check;
    check = a[0]*(a[4]*a[8] - a[5]*a[7])
          - a[1]*(a[3]*a[8] - a[5]*a[6])
          + a[2]*(a[3]*a[7] - a[4]*a[6]);

    ok = det == check;

    return ok;
}

Code from here. You will also find the necessary .hpp files there.

Ashish
You should expand this answer, it's pretty obtuse right now
Daenyth
There you go. I've added some code.
Ashish
+5  A: 

There are problems, that are NP-complete(verifiable in nondeterministic polynomial time). Meaning if input scales, then your computation needed to solve the problem increases more then a lot.

Some NP-hard problems are: Hamiltonian path problem( open img ), Travelling salesman problem( open img )
Some NP-complete problems are: Boolean satisfiability problem (Sat.)( open img ), N-puzzle( open img ), Knapsack problem( open img ), Subgraph isomorphism problem( open img ), Subset sum problem( open img ), Clique problem( open img ), Vertex cover problem( open img ), Independent set problem( open img ), Dominating set problem( open img ), Graph coloring problem( open img ),

Source: link 1, link 2

alt text
Source: link

Margus
You should at least add a link to the [Wikipedia article](http://en.wikipedia.org/wiki/Big_O_notation#Orders_of_common_functions) that you have copied.
Peter Lang
Theres no need to pollute the page with all those examples; or at least don't use the diagrams.
mathepic
I like the examples here. SO should have a way to hide/expand certain parts of a post.
devoured elysium
Note to self: Personally you liked how examples had picture images, but after a while you found out, that lots of people does not. So after +10 down votes, You removed the images. (And added a comic to compensate mental loss).
Margus
NP stands for Nondeterministic **Polynomial**, meaning faster than exponential time (but only in theory). Factorial is slower than exponential, in theory and practice. So, this is totally irrelevant.
Potatoswatter
+7  A: 

See the Orders of common functions section of the Big O Wikipedia article.

According to the article, solving the traveling salesman problem via brute-force search and finding the determinant with expansion by minors are both O(n!).

Bill the Lizard
+2  A: 

In Wikipedia

Solving the traveling salesman problem via brute-force search; finding the determinant with expansion by minors.

http://en.wikipedia.org/wiki/Big_O_notation#Orders_of_common_functions

動靜能量
+2  A: 

Bogosort is the only "official" one I've encountered that ventures into the O(n!) area. But it's not a guaranteed O(n!) as it's random in nature.

MdaG
+2  A: 

I think I'm a bit late, but I find snailsort to be the best example of O(n!) deterministic algorithm. It basically finds the next permutation of an array until it sorts it.

It looks like this:

template <class Iter> 
void snail_sort(Iter first, Iter last)
{
    while (next_permutation(first, last)) {}
}
Gabi Purcaru
A: 

The recursive method you probably learned for taking the determinant of a matrix (if you took linear algebra) takes O(n!) time. Though I dont particularly feel like coding that all up.