[Question]
  [
**Closed**. This question needs [details or clarity](/help/closed-questions). It is not currently accepting answers.
 
 
---
**Want to improve this question?** Add details and clarify the problem by [editing this post](/posts/17456/edit).
Closed 6 years ago.
[Improve this question](/posts/17456/edit) 
Write a program that checks if the integer is a power of 2.
---
*Sample input:*
```
8
```
*Sample output:*
```
Yes
```
---
*Sample input:*
```
10
```
*Sample output:*
```
No
```
---
**Rules:**
* Don't use `+`,`-` operations.
* Use some sort of input stream to get the number. Input is not supposed to be initially stored in a variable.
* The shortest code (in bytes) wins.
You can use any truthy/falsy response (for instance, `true`/`false`). You may assume that input number is greater than `0`.
  
[Answer]
## APL (7)
Yes, that's 7 *bytes*. Assume for the moment that I'm using [IBM codepage 907](http://www-03.ibm.com/systems/resources/systems_i_software_globalization_pdf_cp00907z.pdf) instead of Unicode and then each character is a byte :)
```
0=1|2⍟⎕
```
i.e. `0 = mod(log(input(),2),1)`
[Answer]
## GolfScript, 6 chars, no decrements
```
~.3/&!
```
Here's a solution that doesn't use the `x & (x-1)` method in *any* form. It uses `x & (x/3)` instead. ;-) Outputs `0` if false, `1` if true.
**Explanation:** 
* `~` evals the input string to turn it into a number,
* `.` duplicates it (for the subsequent `&`),
* `3/` divides it by three (truncating down),
* `&` computes the bitwise AND of the divided value with the original, which will be zero if and only if the input is zero or a power of two (i.e. has at most one bit set), and
* `!` logically negates this, mapping zero to one and all other values to zero.
**Notes:**
* Per the clarified rules, [zero is not a valid input](/posts/comments/33451), so this code is OK, even though it outputs `1` if the input is zero.
* If the GolfScript decrement operator `(` is allowed, then the **5-character** solution `~.(&!` [posted by aditsu](/a/17479) is enough. However, it seems to go against [the spirit of the rules](/posts/comments/33459), if not the letter.
* I came up with the `x & (x/3)` trick years ago on the Fun With Perl mailing list. (I'm sure I'm not the first to discover it, but I did (re)invent it independently.) [Here's a link to the original post](http://www.bumppo.net/lists/fun-with-perl/2000/05/msg00065.html), including a proof that it actually works.
[Answer]
# GolfScript, 11 (for 1 (true) and 0 (false))
```
.,{2\?}%?0>
```
Put the number on the stack and then run.
# GolfScript, 22 (for Yes/No)
```
.,{2\?}%?0>'Yes''No'if
```
I love how converting `1`/`0` to `Yes`/`No` takes as much code as the challenge itself :D
Warning: EXTREMELY inefficient ;) It does work fine for numbers up to 10000, but once you get that high you start to notice slight lag.
Explanation:
* `.,`: turns `n` into `n 0..n` (`.` duplicate, `,` 0..n range)
* `{2\?}`: to the power of 2
* `%`: map "power of 2" over "0..n" so it becomes `n [1 2 4 8 16 ...]`
* `?0>`: checks to see if the array contains the number (0 is greater than index)
[Answer]
# Mathematica 28
```
Numerator[Input[]~Log~2]==1
```
For integer powers of 2, the numerator of the base 2 log will be 1 (meaning that the log is a unit fraction).
Here we modify the function slightly to display the presumed input.
We use `#` in place of `Input[]` and add `&` to define a pure function.
It returns the same answer that would be returned if the user input the number in the above function.
```
    Numerator[#~Log~2] == 1 &[1024]
    Numerator[#~Log~2] == 1 &[17]
```
> 
> True  
> 
> False
> 
> 
> 
Testing several numbers at a time.
```
    Numerator[#~Log~2] == 1 &&/@{64,8,7,0}
```
> 
> {True, True, False, False}
> 
> 
> 
[Answer]
# Perl 6 (17 characters)
```
say get.log(2)%%1
```
This program gets a line from STDIN `get` function, calculates logarithm with base 2 on it (`log(2)`), and checks if the result divides by 1 (`%%1`, where `%%` is divides by operator). Not as short as GolfScript solution, but I find this acceptable (GolfScript wins everything anyway), but way faster (even considering that Perl 6 is slow right now).
```
~ $ perl6 -e 'say get.log(2)%%1'
256
True
~ $ perl6 -e 'say get.log(2)%%1'
255
False
```
[Answer]
**Octave (~~15~~ 23)**
EDIT: Updated due to user input requirement;
```
~mod(log2(input('')),1)
```
Lets the user input a value and outputs 1 for true, 0 for false.
Tested in Octave, should work in Matlab also.
[Answer]
## R, 13 11
Based on the Perl solution. Returns `FALSE` or `TRUE`.
```
!log2(i)%%1
```
The parameter `i` represents the input variable.
An alternative version with user input:
```
!log2(scan())%%1
```
[Answer]
# GolfScript, 5
Outputs 1 for true, 0 for false. Based on user3142747's idea:
```
~.(&!
```
Note: `(` is decrement, hopefully it doesn't count as `-` :)  
If it does (and the OP's comments suggest that it might), then please refer to [Ilmari Karonen's solution](https://codegolf.stackexchange.com/a/17526/7416) instead.  
For Y/N output, append `'NY'1/=` at the end (7 more bytes).
[Answer]
## Python, 31
```
print 3>bin(input()).rfind('1')
```
[Answer]
# C, 48
```
main(x){scanf("%i",&x);puts(x&~(x*~0)?"F":"T");}
```
[Answer]
I decided to to use another approach, based on the [*population count*](http://en.wikipedia.org/wiki/Hamming_weight) or *sideways sum* of the number (the number of 1-bits). The idea is that all powers of two have exactly one `1` bit, and no other number does. I added a JavaScript version because I found it amusing, though it certainly won't win any golfing competition.
### J, ~~14~~ 15 chars (outputs 0 or 1)
```
1=##~#:".1!:1]1
```
### JavaScript, 76 chars (outputs true or false)
```
alert((~~prompt()).toString(2).split("").map(Number).filter(Boolean).length)
```
[Answer]
# [Clip](http://esolangs.org/wiki/Clip), ~~9~~ ~~8~~ 7
```
!%lnxWO
```
Reads a number from stdin.
Explanation:
To start with, `Z` = `0`, `W` = `2` and `O` = 1. This allows placing of `W` and `O` next to each other, whereas using `2` and `1` would be interpreted as the number 21 without a separating space (an unwanted extra character).
In Clip, the modulo function (`%`) works on non-integers, so, to work out if some value `v` is an integer, you check if `v` mod 1 = 0. Using Clip syntax, this is written as `=0%v1`. However, as booleans are stored as `1` (or anything else) and `0`, checking if something is equal to `0` is just 'not'ing it. For this, Clip has the `!` operator. In my code, `v` is `lnx2`. `x` is an input from stdin, `n` converts a string to a number and `lab` is log base `b` of `a`. The program therefore translates (more readably) to `0 = ((log base 2 of parseInt(readLine)) mod 1)`.
Examples:
```
8
```
outputs
```
1
```
and
```
10
```
outputs
```
0
```
Edit 1: replaced `0`, `1` and `2` with `Z`, `O` and `W`.
Edit 2: replaced `=Z` with `!`.
Also:
# [Pyth](http://esolangs.org/wiki/Pyth), 5
Compresses the Clip version even further, as Pyth has Q for already evaluated input and a log2(a) function instead of just general log(a, b).
```
!%lQ1
```
[Answer]
**Javascript (37)**
```
a=prompt();while(a>1)a/=2;alert(a==1)
```
Simple script that just divides by 2 repeatedly and checks the remainder.
[Answer]
# Mathematica (21)
```
IntegerQ@Log2@Input[]
```
Without input it is a bit shorter
```
IntegerQ@Log2[8]
```
> 
> True
> 
> 
> 
```
IntegerQ@Log2[7]
```
> 
> False
> 
> 
> 
[Answer]
### Ruby — 17 characters (fourth try)
```
p /.1/!~'%b'%gets
```
My current best is a fusion of @steenslag's answer with my own. Below are my previous attempts.
### Ruby — 19 characters (third try)
```
p /10*1/!~'%b'%gets
```
### Ruby — 22 characters (second try)
```
p !('%b'%gets)[/10*1/]
```
### Ruby — 24 characters (first try)
```
p !!('%b'%gets=~/^10*$/)
```
[Answer]
## JavaScript, ~~41~~ 40 characters
```
l=Math.log;alert(l(prompt())/l(2)%1==0);
```
How this works: you take the logarithm at base 2 using `l(prompt()) / l(2)`, and if that result modulo 1 is equal to zero, then it is a power of 2.
For example: after taking the logarithm of 8 on base `2`, you get `3`. `3 modulo 1` is equal to 0, so this returns true.
After taking the logarithm of 7 on base 2, you get `2.807354922057604`. `2.807354922057604 modulo 1` is equal to `0.807354922057604`, so this returns false.
[Answer]
# JavaScript, 35
Works for bytes.
```
alert((+prompt()).toString(2)%9==1)
```
**46 character version**,
Works for 16 bit numbers.
```
x=(+prompt()).toString(2)%99;alert(x==1|x==10)
```
The trick works in most dynamic languages.
**Explanation:** Convert the number to base 2, interpret that string as base 10, do modulo 9 to get the digit sum, which must be 1.
[Answer]
## Perl 5.10+, 13 + 1 = 14 chars
```
say!($_&$_/3)
```
Uses the same method [from an old FWP thread](http://www.bumppo.net/lists/fun-with-perl/2000/05/msg00065.html) as [my GolfScript entry](/a/17526).
Prints `1` if the input is a power of two, and an empty line otherwise.
Needs to be run with `perl -nE`; the `n` [costs one extra char](//meta.codegolf.stackexchange.com/questions/273/on-interactive-answers-and-other-special-conditions), for a total of 14 chars. Alternatively, here's an **18-character** version that doesn't need the `n`:
```
say!(($_=<>)&$_/3)
```
[Answer]
**python 3, 38**
```
print(1==bin(int(input())).count('1'))
```
**python, 32**
However, the code doesn't work in every version.
```
print 1==bin(input()).count('1')
```
Notice that the solution works also for 0 (print False).
[Answer]
## K/Kona (24 17)
```
d:{(+/(2_vs x))~1
```
Returns 1 if true and 0 if false. Any power of 2 has a single bit equal to 1:
```
2_vs'_(2^'(!10))
(,1
1 0
1 0 0
1 0 0 0
1 0 0 0 0
1 0 0 0 0 0
1 0 0 0 0 0 0
1 0 0 0 0 0 0 0
1 0 0 0 0 0 0 0 0
1 0 0 0 0 0 0 0 0 0)
```
(this prints out all the powers of 2 (from 0 to 9) in binary)
So I sum up all the components of the binary expression of `x` and see if it's equal to 1; if yes then `x=2^n`, otherwise nope.
  
  
...knew I could make it smaller
[Answer]
**C# (54 characters)**
```
 Math.Log(int.Parse(Console.ReadLine()),2)%1==0?"Y":"N"
```
[Answer]
# Rebmu (9 chars)
```
z?MOl2A 1
```
**Test**
```
>> rebmu/args [z?MOl2A 1] 7
== false
>> rebmu/args [z?MOl2A 1] 8 
== true
>> rebmu/args [z?MOl2A 1] 9 
== false
```
[Rebmu](http://rebmu.hostilefork.com/) is a constricted dialect of Rebol. The code is essentially:
```
z? mo l2 a 1  ; zero? mod log-2 input 1
```
**Alternative**
*14 chars—Rebmu does not have a 'mushed' bitwise AND~*
```
z?AND~aTIddA 3
```
In Rebol:
```
zero? a & to-integer a / 3
```
[Answer]
# OCaml - 42 or 45
Since no-one has submitted an OCaml solution, I submit one inspired by nightcrackers C solution.
There is some debate as to whether the operator `-` includes unary negation. Other entries have managed to sidestep the issue by finding a solution that is equally short without unary negation. I instead give two answers:
`let x=read_int()in 0=x land lnot(x* -1);;`
and
`let x=read_int()in 0=x land lnot(x*lnot 0);;`
the `;;` ends a group of statements in the OCaml interpreter and causes the result to be printed as `- : bool = false` or `- : bool = true`, which are clear negative/positive answers as required by the question.
[Answer]
## [GTB](http://timtechsoftware.com/gtb), 46 bytes
```
2→P`N[@N=Pg;1P^2→P@P>1E90g;2]l;2~"NO"&l;1"YES"
```
[Answer]
**Python, 35**
```
print bin(input()).strip('0')=='b1'
```
Doesn't use not only +/- operations, but any math operations aside from converting to binary form.
Other stuff (interesting, but not for competition):
I have also a **regexp version (61)**:
```
import re;print re.match(r'^0b10+$',bin(input())) is not None
```
(Love the idea, but import and match function make it too long)
And nice, but boring **bitwise operations version (31)**:
```
x=input();print x and not x&~-x
```
(yes, it's shorter, but it uses ~-x for decrement which comtains - operation)
[Answer]
**Python 2.7 (~~30~~ ~~29~~ ~~39~~ 37)**
EDIT: Updated due to user input requirement;
```
a=input()
while a>1:a/=2.
print a==1
```
Brute force, try to divide until =1 (success) or <1 (fail)
[Answer]
# Python (33)
```
print int(bin(input())[3:]or 0)<1
```
[Answer]
# Ruby, ~~33~~, ~~28~~, 25
```
p /.1/!~gets.to_i.to_s(2)
```
[Answer]
# APL (12 for 0/1, 27 for yes/no)
```
≠/A=2*0,ιA←⍞ 
```
or, if we must output text:
```
3↑(3x≠/A=2*0,ιA←⍞)↓'YESNO '
```
Read in A. Form a vector 0..A, then a vector 20..2A (yes, that's way more than necessary), then a vector comparing A with each of those (resulting in a vector of 0's and at most one 1), then xor that (there's no xor operator in APL, but ≠ applied to booleans will act as one.) We now have 0 or 1.
To get YES or NO: multiply the 0 or 1 by 3, drop this number of characters from 'YESNO ', then take the first 3 characters of this.
[Answer]
**C, 65 bytes**
```
main(k){scanf("%i",&k);while(k&&!(k%2))k/=2;puts(k==1?"T":"F");}
```
]