Efficient way to multiply with 7

1.9

We can multiply a number by 7 using bitwise operator. First left shift the number by 3 bits (you will get 8n) then subtract the original numberfrom the shifted number and return the difference (8n – n).


Program:

C

# include<stdio.h>

int multiplyBySeven(unsigned int n)
{  
    /* Note the inner bracket here. This is needed 
       because precedence of '-' operator is higher 
       than '<<' */
    return ((n<<3) - n);
}

/* Driver program to test above function */
int main()
{
    unsigned int n = 4;
    printf("%u", multiplyBySeven(n));

    getchar();
    return 0;
}

Python

# Python program to multiply any 
# positive number to 7 

# Function to mutiply any number with 7 
def multiplyBySeven(n):

    # Note the inner bracket here. 
    # This is needed because 
    # precedence of '-' operator is 
    # higher than '<<' 
    return ((n << 3) - n)

# Driver code 
n = 4
print(multiplyBySeven(n))

# This code is contributed by Danish Raza


Output:
28

Time Complexity: O(1)
Space Complexity: O(1)

Note: Works only for positive integers.
Same concept can be used for fast multiplication by 9 or other numbers.

GATE CS Corner    Company Wise Coding Practice

Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.

Recommended Posts:



1.9 Average Difficulty : 1.9/5.0
Based on 74 vote(s)










Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.