Home > Software engineering >  Check whether a given number is a power of two
Check whether a given number is a power of two

Time:09-24

I am trying to write a function which returns a value 1 if the number entered is a power of two, else it returns a value 0.

function val = func_1(num)
   while not(num == 1)
      if num%2~=0
         val=0;
         break
      end
      num=num/2;
      val=1;
   end
end

But unfortunately, the function always return a value 1. Is there any error in the algorithm or the code? Thanks in advance for any help.

CodePudding user response:

In Matlab, % is the comment character. Everything from that point onwards until the end of the line is ignored. This means that this line if num%2~=0 is not doing what you think it does.

Instead, use the mod function. link. In this case, the line in question becomes if mod(num, 2)~=0.

On a separate note, I suspect there is a much more efficient way of doing this. See, for example, here.

  • Related