我们可以使用按位运算运算符将数字乘以7。首先将数字左移3位(您将获得8n),然后从移位后的数字中减去原始数字,然后返回差值(8n – n)。
程序:
CPP
# include
using namespace std;
//c++ implementation
long multiplyBySeven(long 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()
{
long n = 4;
cout<
C
# include
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;
}
Java
// Java program to multiply any
// positive number to 7
class GFG {
static int multiplyBySeven(int n)
{
/* Note the inner bracket here.
This is needed because precedence
of '-' operator is higher
than '<<' */
return ((n << 3) - n);
}
// Driver code
public static void main (String arg[])
{
int n = 4;
System.out.println(multiplyBySeven(n));
}
}
// This code is contributed by Anant Agarwal.
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
C#
// C# program to multiply any
// positive number to 7
using System;
class GFG
{
static int multiplyBySeven(int n)
{
/* Note the inner bracket here. This is needed
because precedence of '-' operator is higher
than '<<' */
return ((n << 3) - n);
}
// Driver code
public static void Main ()
{
int n = 4;
Console.Write(multiplyBySeven(n));
}
}
// This code is contributed by Sam007
PHP
Javascript
输出:
28
时间复杂度: O(1)
空间复杂度: O(1)
注意:仅适用于正整数。
相同的概念可以用于9或其他数字的快速乘法。