/*following is the shortest program that finds whether the entered no. is power of two or not,but i need to add some code(logic) to it.

 

note:- program do not make use of keywords like if ,while ,for ,switch. */

 

#include<stdio.h>

void main()

{

 int n;

 char c[2][23]={"no. is not power of 2","no. is power of 2"};

 scanf("%d",&n);

 printf("%s",c[/*add code*/]);

 }

<< moderator edit: added [co[u][/u]de][/co[u][/u]de] tags >>

can anyone tell me the code i should write in printf statement so as to know that whether the number is power of 2 or not

Recommended Answers

All 9 Replies

Nice Tricks

if ( num & (num-1) == 0)
{
// it is power of 2.
}

if ( num & (num-1) == 0)

Parentheses are important -- here important ones are missing.

inside the add code... put

((n & 1)+1)%2

or if u are allowed to change the char string... swap those two around and u only need

(n & 1)

inside the add code... put

((n & 1)+1)%2

Without context I might then do...

if ( ((num & 1)+1)%2 )
      {
         printf("num = %d\n", num);
      }

Which is horribly wrong.

or if u are allowed to change the char string... swap those two around and u only need

(n & 1)

Again, same reply.

Please stop trying to make correct code incorrect. Or at least attempt to provide enough code to prove your point.

I'm not correcting his code or anything... my stuff is new... just copy paste what i wrote and replace /*add code*/...

as in...

/*following is the shortest program that finds whether the entered no. is power of two or not,but i need to add some code(logic) to it.

note:- program do not make use of keywords like if ,while ,for ,switch. */

#include<stdio.h>

void main()

{

int n;

char c[2][23]={"no. is not power of 2","no. is power of 2"};

scanf("%d",&n);

printf("%s",c[((n & 1)+1)%2]);

}

Wow! 6 and 10 are powers of 2!
void main()!
No code tags!

oops lol was thinking multiples... sorry :rolleyes:

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.