How could I analyze this algorithm using the "Big Oh" notation, and how could I improve the execution time of this algorithm?

The algorithm is explained by:

  • if n is even: return 1 + g (n / 2).
  • if n is odd: return 1 + g (n-1).
  • if n = 1: return 1.

the code:

public static int g(int n)
{
    if (n==1)
        return 1;
    else if (n%2==0)
        return 1 + g(n/2);
    else
        return 1 + g(n-1);
}
+4
source share
3 answers

When a number is equal to even the largest bit in its binary representation, this 0. Dividing the number by 2 removes this zero.

N = 16       => 8       => 4      => 2     => 1
    (10000)2 => (1000)2 => (100)2 => (10)2 => 1

, 1. , . 1 0. , , 2, .

, , 1 s:

1111111111111

, , , 1

1111111111111 decrement it because it is odd
1111111111110 divide it by two because it even 
111111111111

, 1 2 * 1s. 1s log 2 N. , O (logN).

+1

: log (n)

:

n g (n).

*****0 => ***** (left shift)
*****1 => ****0 (change last 1 to 0) => **** (left shift) 

, 2 .

, : 2 * log 2 (n)= O (log 2 (n)).

0

O(lg(n)): 2, 2, , , lg(n). , , 2 ( , ). , 2*log(n) , O(lg(n)).

0
source

Source: https://habr.com/ru/post/1656469/


All Articles