0

The following code give me a O(n). how do I code a for loop that has time complexity of O(c^k)?

int power(int x, unsigned int y)
{
    if( y == 0)
        return 1;
    else if (y%2 == 0)
        return power(x, y/2)*power(x, y/2);
    else
        return x*power(x, y/2)*power(x, y/2);

}
benjamin tan
  • 9
  • 1
  • 3
  • See the answer to this question: http://stackoverflow.com/questions/7055652/real-world-example-of-exponential-time-complexity – Funkytown Jun 23 '13 at 10:59

2 Answers2

1

Not sure what you're asking, but you can clearly modify this code and win a lot by simply getting rid of repeating recursions (not to calculate the same thing twice recursively).

if (y%2 == 0) {
    int res = power(x, y/2);    
    return res * res;
}

writing it this way will allow you to write a while loop instead of recursion.

Tala
  • 8,888
  • 5
  • 34
  • 38
  • if (y%2 == 0) { int res = power(x, y/2); return res * res; } does this give a O(c^k)? – benjamin tan Jun 23 '13 at 11:25
  • is your goal to make the algorithm more complex? why would you need exponential time complexity? – Tala Jun 23 '13 at 11:45
  • public void run(int n) { System.out.println(power(3, n)); } public int power(int c, int n) { int result = 1; for (int i = 0; i < c; i++) { result *= n; } return result; } does this code give me a O(c^k) - exponential time complexity? – benjamin tan Jun 23 '13 at 12:07
  • no, it gives you O(n). to make it exponential you have to make it way more complex. – Tala Jun 23 '13 at 12:22
  • public void run(int n) { for (long i = 1; i <= power(3, n); i++) { System.out.println(i); } } public int power(int c, int n) { int result = 1; for (int i = 0; i < c; i++) { result *= n; } return result; } How abt this code? – benjamin tan Jun 23 '13 at 12:29
  • no. you should read https://en.wikipedia.org/wiki/Computational_complexity_theory – Tala Jun 23 '13 at 12:56
0

O(c^k) - exponential time complexity algorithms are, for example, brute-force search and traveling salesman problems.

I give you an example of brute-force search. If you had a set of characters of length c, and have the password of length k. Then you would need a O(c^k) time to break the password.

darijan
  • 9,725
  • 25
  • 38