C Programming Coding Mathematical Algorithms

C Programming for Efficient way to multiply with 7

C Programming for Efficient way to multiply with 7 - Mathematical Algorithms - We can multiply a number by 7 using bitwise operator. left shift number by 3.

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;
}

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

See also  How to turn off a particular bit in a number

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