Want to win a PS4? Go Premium and enter to win our High-Tech Treats giveaway. Enter to Win

x
?
Solved

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

Posted on 2000-04-12
2
Medium Priority
?
233 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 800 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

VIDEO: THE CONCERTO CLOUD FOR HEALTHCARE

Modern healthcare requires a modern cloud. View this brief video to understand how the Concerto Cloud for Healthcare can help your organization.

Question has a verified solution.

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

Have you thought about creating an iPhone application (app), but didn't even know where to get started? Here's how: ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ Important pre-programming comments: I’ve never tri…
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 opening and reading files in the C programming language.

618 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