Smallest power of 4 greater than or equal to N
Given an integer N, the task is to find the smallest power of four greater than or equal to N.
Examples:
Input: N = 12
Output: 16
24 = 16 which is the next required
greater number after 12.
Input: N = 81
Output: 81
Approach:
- Find the fourth root of the given n.
- Calculate its floor value using floor() function.
- If n is itself a power of four then return n.
- Else add 1 to the floor value.
- Return the fourth power of that number.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
int nextPowerOfFour( int n)
{
int x = floor ( sqrt ( sqrt (n)));
if ( pow (x, 4) == n)
return n;
else {
x = x + 1;
return pow (x, 4);
}
}
int main()
{
int n = 122;
printf ( "%d" , nextPowerOfFour(n));
return 0;
}
|
C
#include <math.h>
#include <stdio.h>
int nextPowerOfFour( int n)
{
int x = floor ( sqrt ( sqrt (n)));
if ( pow (x, 4) == n)
return n;
else {
x = x + 1;
return pow (x, 4);
}
}
int main()
{
int n = 122;
printf ( "%d" , nextPowerOfFour(n));
return 0;
}
|
Java
import java.util.*;
import java.lang.Math;
import java.io.*;
class GFG
{
static int nextPowerOfFour( int n)
{
int x = ( int )Math.floor(Math.sqrt(Math.sqrt(n)));
if (Math.pow(x, 4 ) == n)
return n;
else {
x = x + 1 ;
return ( int )Math.pow(x, 4 );
}
}
public static void main (String[] args)
throws java.lang.Exception
{
int n = 122 ;
System.out.println(nextPowerOfFour(n));
}
}
|
Python3
import math
def nextPowerOfFour(n):
x = math.floor((n * * ( 1 / 2 )) * * ( 1 / 2 ));
if ((x * * 4 ) = = n):
return n;
else :
x = x + 1 ;
return (x * * 4 );
n = 122 ;
print (nextPowerOfFour(n));
|
C#
using System;
class GFG
{
static int nextPowerOfFour( int n)
{
int x = ( int )Math.Floor(Math.Sqrt(Math.Sqrt(n)));
if (Math.Pow(x, 4) == n)
return n;
else
{
x = x + 1;
return ( int )Math.Pow(x, 4);
}
}
public static void Main ()
{
int n = 122;
Console.WriteLine(nextPowerOfFour(n));
}
}
|
Javascript
<script>
function nextPowerOfFour(n)
{
let x = Math.floor(Math.sqrt(
Math.sqrt(n)));
if (Math.pow(x, 4) == n)
return n;
else
{
x = x + 1;
return Math.pow(x, 4);
}
}
let n = 122;
document.write(nextPowerOfFour(n));
</script>
|
Time Complexity: O(logx) where x is sqrt(sqrt(n))
Auxiliary Space: O(1)
Last Updated :
18 Jul, 2022
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...