Solved

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

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

PRTG Network Monitor: Intuitive Network Monitoring

Network Monitoring is essential to ensure that computer systems and network devices are running. Use PRTG to monitor LANs, servers, websites, applications and devices, bandwidth, virtual environments, remote systems, IoT, and many more. PRTG is easy to set up & use.

Question has a verified solution.

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

Suggested Solutions

An Outlet in Cocoa is a persistent reference to a GUI control; it connects a property (a variable) to a control.  For example, it is common to create an Outlet for the text field GUI control and change the text that appears in this field via that Ou…
Preface I don't like visual development tools that are supposed to write a program for me. Even if it is Xcode and I can use Interface Builder. Yes, it is a perfect tool and has helped me a lot, mainly, in the beginning, when my programs were small…
The goal of this video is to provide viewers with basic examples to understand and use pointers in the C programming language.
Video by: Grant
The goal of this video is to provide viewers with basic examples to understand and use for-loops in the C programming language.

770 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