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.
Below is the implementation of the above approach:
# Python 3 program to multiply
# a number with 3.5
def
multiplyWith3Point5(x):
return
(x<<
1
)
+
x
+
(x>>
1
)
# Driver program to
# test above functions
x
=
4
print
(multiplyWith3Point5(x))
Output
14
2. Another way of doing this could be (8*x – x)/2 (See below code).
- C
#include <stdio.h>
int
multiplyWith3Point5(
int
x)
{
return
((x<<3) - x)>>1;
}