Solved

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

Posted on 2000-04-12
2
177 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
Comment Utility
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
Comment Utility
That's too good. I  accept this answer and thanks to you sreenathk

mmt33
0

Featured Post

Why You Should Analyze Threat Actor TTPs

After years of analyzing threat actor behavior, it’s become clear that at any given time there are specific tactics, techniques, and procedures (TTPs) that are particularly prevalent. By analyzing and understanding these TTPs, you can dramatically enhance your security program.

Join & Write a Comment

Summary: This tutorial covers some basics of pointer, pointer arithmetic and function pointer. What is a pointer: A pointer is a variable which holds an address. This address might be address of another variable/address of devices/address of fu…
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…
The goal of this video is to provide viewers with basic examples to understand and use pointers in the C programming language.
The goal of this video is to provide viewers with basic examples to understand and use structures in the C programming language.

772 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

Need Help in Real-Time?

Connect with top rated Experts

11 Experts available now in Live!

Get 1:1 Help Now