Minimum absolute difference between N and any power of 2
Last Updated :
26 Mar, 2021
Given a positive integer N, the task is to find the minimum absolute difference between N and any power of 2.
Examples:
Input: N = 3
Output: 1
Smaller power of 2 nearest to 3 is 2, abs(3 – 2) = 1
Higher power of 2 nearest to 3 is 4, abs(4 – 3) = 1
Input: N = 6
Output: 2
Approach:
- Find the highest power of 2 less than or equal to N and store it in a variable low.
- Find the smallest power of 2 greater than or equal to N and store it in a variable high.
- Now, the answer will be max(N – low, high – N).
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
int prevPowerof2( int n)
{
int p = ( int )log2(n);
return ( int ) pow (2, p);
}
int nextPowerOf2( int n)
{
int p = 1;
if (n && !(n & (n - 1)))
return n;
while (p < n)
p <<= 1;
return p;
}
int minDiff( int n)
{
int low = prevPowerof2(n);
int high = nextPowerOf2(n);
return min(n - low, high - n);
}
int main()
{
int n = 6;
cout << minDiff(n);
return 0;
}
|
Java
import java.util.*;
class GFG
{
static int prevPowerof2( int n)
{
int p = ( int )(Math.log(n) / Math.log( 2 ));
return ( int )Math.pow( 2 , p);
}
static int nextPowerOf2( int n)
{
int p = 1 ;
if ((n == 0 ) && !((n & (n - 1 )) == 0 ))
return n;
while (p < n)
p <<= 1 ;
return p;
}
static int minDiff( int n)
{
int low = prevPowerof2(n);
int high = nextPowerOf2(n);
return Math.min(n - low, high - n);
}
public static void main (String[] args)
{
int n = 6 ;
System.out.println(minDiff(n));
}
}
|
Python3
from math import log
def prevPowerof2(n):
p = int (log(n))
return pow ( 2 , p)
def nextPowerOf2(n):
p = 1
if (n and (n & (n - 1 )) = = 0 ):
return n
while (p < n):
p << = 1
return p
def minDiff(n):
low = prevPowerof2(n)
high = nextPowerOf2(n)
return min (n - low, high - n)
n = 6
print (minDiff(n))
|
C#
using System;
class GFG
{
static int prevPowerof2( int n)
{
int p = ( int )(Math.Log(n) / Math.Log(2));
return ( int )Math.Pow(2, p);
}
static int nextPowerOf2( int n)
{
int p = 1;
if ((n == 0) && !((n & (n - 1)) == 0))
return n;
while (p < n)
p <<= 1;
return p;
}
static int minDiff( int n)
{
int low = prevPowerof2(n);
int high = nextPowerOf2(n);
return Math.Min(n - low, high - n);
}
public static void Main (String []args)
{
int n = 6;
Console.WriteLine(minDiff(n));
}
}
|
Javascript
<script>
function prevPowerof2(n)
{
var p = parseInt(Math.log(n)/Math.log(2));
return parseInt(Math.pow(2, p));
}
function nextPowerOf2(n)
{
var p = 1;
if (n && !(n & (n - 1)))
return n;
while (p < n)
p <<= 1;
return p;
}
function minDiff(n)
{
var low = prevPowerof2(n);
var high = nextPowerOf2(n);
return Math.min(n - low, high - n);
}
var n = 6;
document.write(minDiff(n));
</script>
|
Time Complexity: O(log N)
Auxiliary Space: O(1)
Share your thoughts in the comments
Please Login to comment...