Generate first K multiples of N using Bitwise operators
Last Updated :
02 Nov, 2021
Given an integer N, the task is to print the first K multiples of N using Bitwise Operators.
Examples:
Input: N = 16, K = 7
Output:
16 * 1 = 16
16 * 2 = 32
16 * 3 = 48
16 * 4 = 64
16 * 5 = 80
16 * 6 = 96
16 * 7 = 112
Input: N = 7, K = 10
Output:
7 * 1 = 7
7 * 2 = 14
7 * 3 = 21
7 * 4 = 28
7 * 5 = 35
7 * 6 = 42
7 * 7 = 49
7 * 8 = 56
7 * 9 = 63
7 * 10 = 70
Approach:
Follow the steps below to solve the problem:
- Iterate up to K.
- For each iteration, print current value of N.
- Then, calculate the sum of 2i for every ith set bit of N. Add this sum to N and repeat from the step above.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
void Kmultiples( int n, int k)
{
int a = n;
for ( int i = 1; i <= k; i++) {
cout << n << " * " << i << " = "
<< a << endl;
int j = 0;
while (n >= (1 << j)) {
a += n & (1 << j);
j++;
}
}
}
int main()
{
int N = 16, K = 7;
Kmultiples(N, K);
return 0;
}
|
Java
import java.util.*;
class GFG{
static void Kmultiples( int n, int k)
{
int a = n;
for ( int i = 1 ; i <= k; i++)
{
System.out.print(n+ " * " + i+ " = "
+ a + "\n" );
int j = 0 ;
while (n >= ( 1 << j))
{
a += n & ( 1 << j);
j++;
}
}
}
public static void main(String[] args)
{
int N = 16 , K = 7 ;
Kmultiples(N, K);
}
}
|
Python3
def Kmultiples(n, k):
a = n
for i in range ( 1 , k + 1 ):
print ( "{} * {} = {}" . format (n, i, a))
j = 0
while (n > = ( 1 << j)):
a + = n & ( 1 << j)
j + = 1
N = 16
K = 7
Kmultiples(N, K)
|
C#
using System;
class GFG{
static void Kmultiples( int n, int k)
{
int a = n;
for ( int i = 1; i <= k; i++)
{
Console.Write(n + " * " + i +
" = " + a + "\n" );
int j = 0;
while (n >= (1 << j))
{
a += n & (1 << j);
j++;
}
}
}
public static void Main(String[] args)
{
int N = 16, K = 7;
Kmultiples(N, K);
}
}
|
Javascript
<script>
function Kmultiples(n , k)
{
var a = n;
for (i = 1; i <= k; i++)
{
document.write(n+ " * " + i+ " = "
+ a + "<br>" );
var j = 0;
while (n >= (1 << j))
{
a += n & (1 << j);
j++;
}
}
}
var N = 16, K = 7;
Kmultiples(N, K);
</script>
|
Output:
16 * 1 = 16
16 * 2 = 32
16 * 3 = 48
16 * 4 = 64
16 * 5 = 80
16 * 6 = 96
16 * 7 = 112
Time Complexity: O(Klog2N)
Auxiliary Space: O(1)
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...