C # Efficient Power Based Algorithm

I look The most efficient way to implement the integer power function pow (int, int) .

This is the answer they received.

I am trying to get it to work in C #, but I am comparing int with bool and all this other., And I can’t understand why they are comparing, and 1 would it mean and true? What is the meaning of this. It does not seem effective.

 int ipow(int base, int exp) 
 { 
     int result = 1; 
     while (exp) 
     { 
         if (exp & 1) 
             result *= base; 
         exp >>= 1; 
         base *= base; 
     } 

return result; 

}

I am doing exp == by comparison, but I'm still there, and I don't know if I need this.

Does anyone know what is 1 in "if (exp and 1)"? Or if I need it? I do not see the use.

+3
source share
4 answers

C ++ if/while " ".

, :

while (exp != 0)

if ((exp & 1) != 0) // If exp is odd

base:)

, #, .

+8

# :

int ipow(int base, int exp) {
   int result = 1; 
   while (exp > 0) {
      if ((exp & 1) != 0) { 
         result *= base;
      } 
      exp >>= 1; 
      base *= base; 
   } 
   return result; 
}

( , base , , C.)

& (exp 1), . , exp.

, , exp , exp.

exp, , 21, 10101 , 16 + 4 + 1. , 21 , 16 *, 4 * 1 *.

+5

'&' . '& &' . ,

int a = 5, b = 1;
int c = a & b;

'a' 00000101 , b - 00000001. & b, . "anded", . C 00000001. , a B b - 1, .

or ('|').

int d = a | b; //d = 00000101

beacause OR , ;

+1

, , , C . , int 1 AND , .

C # will not do the same, you need to think about the algorithm here

0
source

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


All Articles