0
int num = Convert.ToInt32(Console.ReadLine());
for (int i = 2; i <=num; i*=2)
{
  if (i==num)
  {
    Console.WriteLine("It is power of 2");
  }
  else if (i!=num)
  {
    Console.WriteLine("It isn't power of 2");
  }
}  

Hello, what I want to do is determine if a number is a power of 2 or not. As you have seen in the code and may recognized, the problem that comes up is, for example, if I input 16 it will output

It isn't power of 2

It isn't power of 2

It isn't power of 2

It is power of 2

Because by that, the first three values of i are 2, 4 and 8, and the last one 16. All said, how i do to refer to the last value of i

  • 3
    There's a simple test; Does subtracting one cause all 1's to flip to 0's. `(X & (X -1)) == 0` – Jeremy Lakeman May 10 '21 at 02:55
  • 2
    Your actual problem, is that you are logging within the loop. Don't do that. Set a result flag, break out of the loop and then log. – Jeremy Lakeman May 10 '21 at 02:56
  • Note that your loop does not handle negatives, and has undefined behavior if testing very large integers. Also, from a stylistic point, you should avoid specifying the exact opposite condition in `else if`. Here, `else` would be sufficient. – paddy May 10 '21 at 02:56
  • This is the perfect time for you to learn how to write a function for checking for a power of two and use it with your input. – John Alexiou May 10 '21 at 02:59
  • @paddy It's C# so Convert will throw an `OverflowException`. – IllusiveBrian May 10 '21 at 03:01
  • Oh, I thought I was viewing only C++ tags. My bad. – paddy May 10 '21 at 03:02

0 Answers0