File size: 1,330 Bytes
d924141 32f2e18 d924141 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 |
import random
title = "Subtraction in Base 2 Using 2's Complement"
description = "This module teaches subtraction in binary using the 2's complement method, which allows subtraction to be performed as an addition operation."
def generate_question():
num1 = random.randint(1, 7)
num2 = random.randint(1, 7)
result = num1 - num2
bit_length = 4
if result >= 0:
binary_result = bin(result)[2:].zfill(bit_length)
else:
binary_result = bin((1 << bit_length) + result)[2:]
question = f"Subtract {num2} from {num1} in base 2 using 2's complement method."
correct_answer = binary_result
options = [correct_answer]
# Generate incorrect options
while len(options) < 5:
fake_option = bin(random.randint(-7, 7) & 0xF)[2:]
if fake_option not in options:
options.append(fake_option)
random.shuffle(options)
explanation = (
f"The result of subtracting {num2} from {num1} in base 2 using 2's complement is {binary_result}."
"\n\n**Step-by-step solution:**\n"
"1. Find the 2's complement of the subtracted number.\n"
"2. Add it to the first number.\n"
"3. If there's a carry, discard it. The result is the binary difference."
)
return question, options, correct_answer, explanation
|