multiply by 7 Algorithm
The multiply by 7 algorithm is a simple, yet efficient technique used to multiply any given number with seven. This algorithm leverages basic arithmetic operations such as addition, multiplication, and bit manipulation to perform the multiplication without using the conventional multiplication process. The algorithm is particularly useful for optimizing code in computer programming, as it reduces the computational complexity of the multiplication process and speeds up the execution time, especially when dealing with large numbers.
To implement the multiply by 7 algorithm, one starts by taking the given number and performing a left bit shift operation by three places, which is equivalent to multiplying the number by 2^3 or 8. Next, subtract the original number from the result obtained after the bit shift operation. The final result is the product of the original number and 7. This algorithm can be easily implemented in various programming languages using bitwise operators, and it provides a fast and efficient alternative to the traditional multiplication process. The algorithm's simplicity and improved performance make it an attractive option for computer programmers looking to optimize their code and enhance the overall efficiency of their applications.
/**
* Problem : Muliply a number by 7 by using bit manipulation.
* Approach : left shift n by 3 --> 8n
* Therefore 7n = 8n - n;
*/
#include <iostream>
int multiply_by_7( int number )
{
return ((number << 3) - number);
}
int main()
{
std::cout << "Enter a number:";
int num;
std::cin >> num;
std::cout << "7 x " << num << " = "
<< multiply_by_7(num) << std::endl;
return 0;
}