My math background is not so good, this is my attempt to write the JAVA code with runtime proportion to different input .
With n^2/3. Since n^2/3 = cube root n * cube root n, hence I can write
public void test(int n){
for (int i = 0; i*i*i < n; i++) {
for (int j = 0; j*j*j < n; j++) {
count ++;
}
}
}
With 4^n. Can i use Fibonnaci method?
public int fibonnaci(int n) {
if (n <= 1) {
return 1;
} else {
return fibonnaci(n - 2) + fibonnaci(n - 1);
}
}
May I know if my code above is correct? thanks much!
The first one is correct, and really well thought.
The second one is not. That algorithm to calculate fibs has much higher time complexity than O(n^4) (EDIT: which was what was being asked when I wrote this answer -- the question has been updated meanwhile). It is not even polynomial. The reasoning is as follows (notation #fib(x): number of times fib is called to calculate fib(x)):
So, you have:
From this, it would be a reasonable guess that calculating fib(i) takes "about" (actually, just a little less than) 2 times the time to calculate fib(i-1). Hence, you could "guess" that O(#fib(i)) = O(2^i). This is the correct answer, which you can prove easily by induction.
Just to finish about the Fibonacci Sequence, there are much faster algorithms to calculate the n-th number. For instance, an algorithm with linear time (ie, O(n)) is to memoize that function you wrote (ie, make it consult a Map to check if it know the result for n, is so return it immediately, otherwise, calculate it, store it and return it). There's also a closed formula to calculate the n-th fib, therefore a constant-time algorithm (ie, O(1)).
Finally, an example of O(n^4) algorithm is anything with 4 inner loops, each loop running "about" n times.
For instance, calculate the volume of n cubes of side n (in a non-optimal way):
int volume = 0;
for (int cube = 0; cube < n; cube++)
for (int x = 0; x < n; x++)
for (int y = 0; y < n; y++)
for (int z = 0; z < n; z++)
volume++;
return volume;
Are you just writing any code which takes time-complexity of that big-o bound?
Than for #1, yes, it would take O(n^(2/3))
.
But for #2, your code would take O(2^n)
, and theta(1.6...^n)
, and 1.6.. is the famous golden-ratio number.
reference: Computational complexity of Fibonacci Sequence
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With