user13149212
user13149212

Reputation:

How do I break an infinite Python loop?

I'm looking to fix the following code, so that it can finish successfully for all numbers listed. How can I break the infinite loop that's present? Furthermore, how can I return print(is_power_of_two(8)) as True?

  # Check if the number can be divided by two without a remainder
  while n % 2 == 0:
    n = n / 2
  # If after dividing by two the number is 1, it's a power of two
  if n == 1:
    return True
  return False


print(is_power_of_two(0)) # Should be False
print(is_power_of_two(1)) # Should be True
print(is_power_of_two(8)) # Should be True
print(is_power_of_two(9)) # Should be False

Upvotes: 0

Views: 10701

Answers (6)

user14552633
user14552633

Reputation: 1

def is_power_of_two(n):
  # Check if the number can be divided by two without a remainder
  while n % 2 == 0 and n!=0:
    n = n / 2
  # If after dividing by two the number is 1, it's a power of two
  if n == 1:
    return True
  return False
  

print(is_power_of_two(0)) # Should be False
print(is_power_of_two(1)) # Should be True
print(is_power_of_two(8)) # Should be True
print(is_power_of_two(9)) # Should be False

Upvotes: 0

Mirror Sujon
Mirror Sujon

Reputation: 11

def is_power_of_two(n):

 #Check Number for Zero
  if n==0:
    return False
  else:
    # Check if the number can be divided by two without a remainder
    while n % 2 == 0:
      n = n / 2 
    # If after dividing by two the number is 1, it's a power of two
    if n == 1:
      return True
    return False

Upvotes: 0

Prajapati Rahul
Prajapati Rahul

Reputation: 11

def is_power_of_two(n):
  # Check if the number can be divided by two without a remainder
  while n!=0 and (n % 2 == 0 or 2%n==0):
    n = n / 2
    return True
  return False
  

Upvotes: 1

your while condition should be :

# Check if the number can be divided by two without a remainder
  while n % 2 == 0 and n >1:
    n = n / 2

cause for the moment your code infinitely loops when n=1 cause 1%2 = 1

Upvotes: 2

zmbq
zmbq

Reputation: 39013

Add and n != 0 to the while condition, so the loop will halt when n is zero.

Upvotes: 1

import math    
math.log2(number).is_integer()

Use this. From Check if a given number is power of two in Python

Upvotes: 0

Related Questions