Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Function Name: powerOfTwo Inputs: 1. (double) A positive whole number Outputs: 1

ID: 668944 • Letter: F

Question

Function Name: powerOfTwo

Inputs:

1. (double) A positive whole number

Outputs:

1. (logical) A logical value specifying if the input is a power of two

Function Description:

For all our computations, we have been using the base-10 decimal number system. However, computers (and MATLAB!) store numbers using the base-2 system, called binary. A binary number consists of multiple bits of either 0 or 1. Each bit n represents the decimal value 2n, and a binary number can be converted to decimal by adding all the powers of two corresponding to each bit that is a 1.

For example, the decimal number 214 in binary is 11010110.

11010110 (binary) = 27 + 26 + 24 + 22 + 21 = 128 + 64 + 16 + 4 + 2 = 214 (decimal)

Using logical indexing, write a MATLAB function that calculates if a decimal number is a power of two. Return a logical (true or false) value specifying whether or not the decimal number is a power of two.

Notes:

Since it has not been taught in class, you should not use iteration to solve this problem.

You may not use the log(), log2(), or dec2binvec() functions.

You will only be provided positive whole numbers. There are no negative powers of two!

Hints:

The dec2bin() function will be useful. Pay attention to the output!

Explanation / Answer

message="enter number"
num = input(message)
%converting the number into binary format
str = dec2bin(num)
%if the number is power of 2 the binary format of that number always have only one '1'
%in it's 1st position and remaining all are '0's if the maximum position of 1 is 1
%number is power of 2
%we are checking the same condition below
if max(findstr(str,'1'))==1
output = "true";
else
output = "false";
end
output