I don't really understand how this code functions:
static long power2(int n, int e){
long res = 1;
while (e > 0) {
if (e % 2 == 0){
n = n * n;
e = e / 2;
} else {
res = res * n;
e = e - 1;
}
}
return res;
}
Overall I get the code but I have troubles understanding the if statement, for example power2(2,4): first the if statement is entered because e % 2 == 0 is true, but the else statement is entered somehow (I wrote a print statement and it was printed ) and I do not get why. It would make sense to me if e was decremented in the if statement but that is not the case. So that means e was somehow decremented in the if statement, right? I would have thought that it was an infinite loop because e%2==0 keeps being true in this case (2,4) but the right answer 16 is printed after running this code and I have trouble understanding how this works.
Aucun commentaire:
Enregistrer un commentaire