Hey folks,
Given an integer x, write a function that multiplies x with 3.5 and returns the integer result. You are not allowed to use %, /, *.
Examples : Input: 2 Output: 7 Input: 5 Output: 17 (Ignore the digits after decimal point)
Solution:
1. We can get x3.5 by adding 2x, x and x/2. To calculate 2x, left shift x by 1 and to calculate x/2, right shift x by 2. The function should not use any of the arithmetic operators (+, ++, –, -, … etc). Sum of two bits can be obtained by performing XOR (^) of the two bits. Carry bit can be obtained by performing AND (&) of two bits. We can extend this logic for integers. If x and y don’t have set bits at same position(s), then bitwise XOR (^) of x and y gives the sum of x and y. To incorporate common set bits also, bitwise AND (&) is used. Bitwise AND of x and y gives all carry bits. We calculate (x & y) << 1 and add it to x ^ y to get the required result. The idea is to use subtractor logic. Write a program to subtract one from a given number. The idea is to use bitwise operators. Like addition, Write a function Add() that returns sum of two integers. The function should not use any of the arithmetic operators (+, ++, –, -, … etc). Sum of two bits can be obtained by performing XOR (^) of the two bits. Carry bit can be obtained by performing AND (&) of two bits. We can extend this logic for integers. If x and y don’t have set bits at same position(s), then bitwise XOR (^) of x and y gives the sum of x and y. To incorporate common set bits also, bitwise AND (&) is used. Bitwise AND of x and y gives all carry bits. We calculate (x & y) << 1 and add it to x ^ y to get the required result. The idea is to use subtractor logic. The use of operators like ‘+’, ‘-‘, ‘’, ‘/’, ‘++’, ‘–‘ …etc. are not allowed.
Another way of doing this could be by doing a binary multiplication by 7 then divide by 2 using only <<, ^, &, and >>.
But here we have to mention that only positive numbers can be passed to this method.
Below is the implementation of the above approach:
# Python3 program for the above approach
# Function to multiple number
# with 3.5
def multiplyWith3Point5(x):
r = 0
# The 3.5 is 7/2, so multiply
# by 7 (x * 7) then
# divide the result by 2
# (result/2) x * 7 -> 7 is
# 0111 so by doing mutiply
# by 7 it means we do 2
# shifting for the number
# but since we doing
# multiply we need to take
# care of carry one.
x1Shift = x << 1
x2Shifts = x << 2
r = (x ^ x1Shift) ^ x2Shifts
c = (x & x1Shift) | (x & x2Shifts) | (x1Shift & x2Shifts)
while (c > 0 ):
c << = 1
t = r
r ^ = c
c & = t
# Then divide by 2
# r / 2
r = r >> 1
return r
# Driver Code
if __name__ = = '__main__' :
print (multiplyWith3Point5( 5 ))
Output
17