Multiply a given Integer with 3.5
Given a 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 x*3.5 by adding 2*x, x and x/2. To calculate 2*x, left shift x by 1 and to calculate x/2, right shift x by 2.
C++
// C++ program to multiply // a number with 3.5 #include <bits/stdc++.h> int multiplyWith3Point5(int x) { return (x<<1) + x + (x>>1); } /* Driver program to test above functions*/int main() { int x = 4; printf("%d", multiplyWith3Point5(x)); getchar(); return 0; } |
chevron_right
filter_none
Java
// Java Program to multiply // a number with 3.5 class GFG { static int multiplyWith3Point5(int x) { return (x<<1) + x + (x>>1); } /* Driver program to test above functions*/ public static void main(String[] args) { int x = 2; System.out.println(multiplyWith3Point5(x)); } } // This code is contributed by prerna saini. |
chevron_right
filter_none
Python3
# 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)) # This code is contributed by # Smitha Dinesh Semwal |
chevron_right
filter_none
C#
// C# Program to multiply // a number with 3.5 using System; class GFG { static int multiplyWith3Point5(int x) { return (x<<1) + x + (x>>1); } /* Driver program to test above functions*/ public static void Main() { int x = 2; Console.Write(multiplyWith3Point5(x)); } } // This code is contributed by Sam007 |
chevron_right
filter_none
PHP
<?php // PHP program to multiply // a number with 3.5 function multiplyWith3Point5( $x) { return ($x << 1) + $x + ($x >> 1); } // Driver Code $x = 4; echo multiplyWith3Point5($x); // This code is contributed by vt_m. ?> |
chevron_right
filter_none
2. Another way of doing this could be (8*x – x)/2 (See below code). Thanks to Ajaym for suggesting this.
#include <stdio.h> int multiplyWith3Point5(int x) { return ((x<<3) - x)>>1; } |
chevron_right
filter_none
Please write comments if you find the above code/algorithm incorrect, or find better ways to solve the same problem
Recommended Posts:
- Efficient way to multiply with 7
- Check for Integer Overflow
- Count set bits in an integer
- Compute the integer absolute value (abs) without branching
- Russian Peasant (Multiply two numbers using bitwise operators)
- Multiply a number with 10 without using multiplication operator
- How to swap two bits in a given integer?
- Next greater integer having one more number of set bits
- Previous smaller integer having one less number of set bits
- Find One's Complement of an Integer
- Count set bits in an integer using Lookup Table
- Multiply any Number with 4 using Bitwise Operator
- Minimum numbers needed to express every integer below N as a sum
- Multiply a number by 15 without using * and / operators
Improved By : vt_m



