Solved

Simplest code for checking if a number is 2 to the power n?

Posted on 2000-04-12
2
211 Views
Last Modified: 2010-04-15
Hello,
  I am new to C language. I just know printf and scanf. I need some code very urgently. Can you give me simplese code possible (Not more than 4 lines), to check whether a number is 2 to the power n or not.
Eg :
For the numbers 2, 4, 128 it should return 1;

Thanks in advance,
MMT33
0
Comment
Question by:mmt33
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
2 Comments
 
LVL 3

Accepted Solution

by:
sreenathk earned 200 total points
ID: 2708748
It is really simple. If you know bitwise operators, you have one line solution. As you are newbie, you can learn it later.
But check the answer,

Suppose n is the variable which contains the number,,,,

if (( n & (n-1)) == 0)
{
  printf("It is in the form of 2 to the power of n\r\n");
return(1);
else
return(0);
}

This works perfectly,

Sreenath
0
 

Author Comment

by:mmt33
ID: 2708759
That's too good. I  accept this answer and thanks to you sreenathk

mmt33
0

Featured Post

Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Windows programmers of the C/C++ variety, how many of you realise that since Window 9x Microsoft has been lying to you about what constitutes Unicode (http://en.wikipedia.org/wiki/Unicode)? They will have you believe that Unicode requires you to use…
This is a short and sweet, but (hopefully) to the point article. There seems to be some fundamental misunderstanding about the function prototype for the "main" function in C and C++, more specifically what type this function should return. I see so…
Video by: Grant
The goal of this video is to provide viewers with basic examples to understand and use nested-loops in the C programming language.
The goal of this video is to provide viewers with basic examples to understand and use switch statements in the C programming language.

724 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question