Welcome to today's lesson! We're going to dive into an interesting topic: Multiplying a number by 7 without using the multiplication operator (*). This is a great exercise to understand bitwise operations, a fundamental concept in computer programming. Let's get started!
Before we dive into multiplying by 7, let's first understand what bitwise operations are. In simple terms, they are mathematical operations that work on the individual bits (0s and 1s) of a number.
Here's a quick recap of the four basic bitwise operators:
š Note: You can use these operators on a single number or two numbers to perform bitwise operations.
Now that you have a grasp of bitwise operations, let's see how we can use them to multiply a number by 7. The key lies in understanding the binary representation of numbers and bit shifting.
Every number has a binary representation. For example, the binary representation of 7 is 0111 (read from right to left).
By shifting the binary representation of a number one place to the left (using the << operator), we effectively multiply the number by 2.
Let's test this with an example:
num = 5 # binary: 0101
shifted_num = num << 1 # binary: 1010 (5 * 2)So, to multiply by 7, we can shift the bits of a number three places to the left (since 7 is 2^3). But wait! Shifting a number 3 places to the left will multiply it by 8, not 7. So, we'll subtract 1 from the result to get the desired multiplication.
Here's the complete function:
def multiply_by_seven(num):
shifted_num = num << 3
return shifted_num - num
# Testing the function
print(multiply_by_seven(5)) # Output: 28š Note: The function works for numbers between 0 and 127 (since shifting 3 places to the left for numbers greater than 127 would result in an overflow).
Now that you've learned the trick, let's test your understanding with a quick quiz:
What is the output of `multiply_by_seven(3)`?
In this lesson, we learned an unconventional yet exciting way to multiply a number by 7 without using the multiplication operator (*). We also delved into bitwise operations and how shifting bits can help us perform arithmetic operations.
Remember, practice is key to mastering these concepts. Keep experimenting with different numbers and functions to solidify your understanding. Happy coding! šÆ
š Note: If you're looking for more exercises or want to explore bitwise operations in depth, visit the Bitwise Operations section of our website.