1

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.

1
  • 1
    Unless you really want to do it by hand, you can use num==2^nextpow2(num) Commented Sep 20, 2021 at 9:48

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks @RPM. I missed that comments are made using %.
2

In Matlab, for any integer num:

val=(num~=0 & (bitand(num,num-1)==0));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.