Solved

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

Posted on 2000-04-12
2
201 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
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

Master Your Team's Linux and Cloud Stack

Come see why top tech companies like Mailchimp and Media Temple use Linux Academy to build their employee training programs.

Question has a verified solution.

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

This tutorial is posted by Aaron Wojnowski, administrator at SDKExpert.net.  To view more iPhone tutorials, visit www.sdkexpert.net. This is a very simple tutorial on finding the user's current location easily. In this tutorial, you will learn ho…
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.

792 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