58.5k views
2 votes
Write a program that takes in a positive integer as input, and outputs a string of 1's and O's representing the integer in binary. For an integer x, the algorithm is:

As long as x is greater than 0 Output x 8 2 (remainder is either 0 or 1)
x = x 1/2

1 Answer

0 votes

Final answer:

To convert a positive integer to binary, you can use the algorithm provided. Here's a Python program that implements this algorithm.

Step-by-step explanation:

To convert a positive integer to binary, you can use the algorithm provided. Here's a Python program that implements this algorithm:

def integer_to_binary(n):
binary = ''
while n > 0:
remainder = n % 2
binary = str(remainder) + binary
n = n // 2
return binary

# Test the function
num = int(input('Enter a positive integer: '))
binary_representation = integer_to_binary(num)
print(binary_representation)

In this program, the function integer_to_binary takes a positive integer as input and uses a while loop to repeatedly divide the integer by 2 and keep track of the remainders. The remainders are concatenated to form the binary representation of the integer.

User Kevin Swann
by
7.9k points