Algorithm Bit Algorithms: Integer

Multiply a given Integer with 3.5

Multiply a given Integer with 3.5 - Bit Algorithm - Given a integer x, write a function that multiplies x with 3.5 and returns the integer result.

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
#include <stdio.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;
}

2. Another way of doing this could be (8*x – x)/2 (See below code). Thanks to ajaym for suggesting this.

c
#include <stdio.h>
int multiplyWith3Point5(int x)
{
  return ((x<<3) - x)>>1;
}
See also  Count total set bits in all numbers from 1 to n

About the author

Venkatesan Prabu

Wikitechy Founder, Author, International Speaker, and Job Consultant. My role as the CEO of Wikitechy, I help businesses build their next generation digital platforms and help with their product innovation and growth strategy. I'm a frequent speaker at tech conferences and events.

Add Comment

Click here to post a comment