program PowerOfTwoCheck;
uses Math;
function IsPowerOfTwoA(x: Integer): Boolean;
var
count, n: Integer;
begin
if x <= 0 then
Exit(False);
count := 0;
n := x;
while n > 0 do
begin
if (n and 1) = 1 then
Inc(count);
n := n shr 1;
end;
IsPowerOfTwoA := count = 1;
end;
function IsPowerOfTwoB(x: Integer): Boolean;
begin
IsPowerOfTwoB := (x > 0) and ((x and (x - 1)) = 0);
end;
function IsPowerOfTwoC(x: Integer): Boolean;
begin
if x <= 0 then
Exit(False);
while (x mod 2 = 0) do
x := x div 2;
IsPowerOfTwoC := x = 1;
end;
function IsPowerOfTwoD(x: Integer): Boolean;
var
logv: Double;
begin
if x <= 0 then
Exit(False);
logv := Ln(x) / Ln(2);
IsPowerOfTwoD := Abs(logv - Round(logv)) < 1e-10;
end;
var
test1, test2: Integer;
begin
test1 := 16; // true
test2 := 18; // false
WriteLn('A: ', IsPowerOfTwoA(test1), ', ', IsPowerOfTwoA(test2));
WriteLn('B: ', IsPowerOfTwoB(test1), ', ', IsPowerOfTwoB(test2));
WriteLn('C: ', IsPowerOfTwoC(test1), ', ', IsPowerOfTwoC(test2));
WriteLn('D: ', IsPowerOfTwoD(test1), ', ', IsPowerOfTwoD(test2));
end.
{
OUTPUT:
A: TRUE, FALSE
B: TRUE, FALSE
C: TRUE, FALSE
D: TRUE, FALSE
}