给定正整数N和K ,任务是找出K的最大和最小幂分别大于或小于N。
例子:
Input: N = 3, K = 2
Output: 2 4
Highest power of 2 less than 3 = 2
Smallest power of 2 greater than 3 = 4
Input: N = 6, K = 3
Output: 3 9
Highest power of 3 less than 6 = 2
Smallest power of 3 greater than 6 = 9
方法:
- 计算以底数K为单位的N的对数( log K N )以获得指数幂,以使升至该指数的K为K的最高幂,小于N。
- 对于K的最小乘方小于N,找到从上一步计算出的K的下一个乘方
下面是上述方法的实现:
C++
// C++ implementation of the approach
#include
using namespace std;
// Function to return the highest power
// of k less than or equal to n
int prevPowerofK(int n, int k)
{
int p = (int)(log(n) / log(k));
return (int)pow(k, p);
}
// Function to return the smallest power
// of k greater than or equal to n
int nextPowerOfK(int n, int k)
{
return prevPowerofK(n, k) * k;
}
// Function to print the result
void printResult(int n, int k)
{
cout << prevPowerofK(n, k)
<< " " << nextPowerOfK(n, k)
<< endl;
}
// Driver code
int main()
{
int n = 25, k = 3;
printResult(n, k);
return 0;
}
Java
// Java implementation of the approach
import java.io.*;
class GFG{
// Function to return the highest power
// of k less than or equal to n
static int prevPowerofK(int n, int k)
{
int p = (int)(Math.log(n) / Math.log(k));
return (int) Math.pow(k, p);
}
// Function to return the smallest power
// of k greater than or equal to n
static int nextPowerOfK(int n, int k)
{
return prevPowerofK(n, k) * k;
}
// Function to print the result
static void printResult(int n, int k)
{
System.out.println(prevPowerofK(n, k) + " " +
nextPowerOfK(n, k));
}
// Driver Code
public static void main (String args[])
{
int n = 25, k = 3;
printResult(n, k);
}
}
// This code is contributed by shivanisinghss2110
Python3
# Python3 implementation of the approach
import math
# Function to return the highest power
# of k less than or equal to n
def prevPowerofK(n, k):
p = int(math.log(n) / math.log(k))
return int(math.pow(k, p))
# Function to return the smallest power
# of k greater than or equal to n
def nextPowerOfK(n, k):
return prevPowerofK(n, k) * k
# Function to print the result
def printResult(n, k):
print(prevPowerofK(n, k), nextPowerOfK(n, k))
# Driver code
n = 6
k = 3
printResult(n, k)
# This code is contributed by divyamohan123
C#
// C# implementation of the approach
using System;
class GFG{
// Function to return the highest power
// of k less than or equal to n
static int prevPowerofK(int n, int k)
{
int p = (int)(Math.Log(n) / Math.Log(k));
return (int) Math.Pow(k, p);
}
// Function to return the smallest power
// of k greater than or equal to n
static int nextPowerOfK(int n, int k)
{
return prevPowerofK(n, k) * k;
}
// Function to print the result
static void printResult(int n, int k)
{
Console.WriteLine(prevPowerofK(n, k) + " " +
nextPowerOfK(n, k));
}
// Driver Code
public static void Main(String []args)
{
int n = 25, k = 3;
printResult(n, k);
}
}
// This code is contributed by gauravrajput1
Javascript
输出:
9 27