题目:完美的幂指数
题目描述:
A perfect power is a classification of positive integers:
In mathematics, a perfect power is a positive integer that can be expressed as an integer power of another positive integer. More formally, n is a perfect power if there exist natural numbers m > 1, and k > 1 such that m^k = n.
Your task is to check wheter a given integer is a perfect power. If it is a perfect power, return a pair m
and k
with m^k = n as a proof. Otherwise return Nothing
, Nil
, null
, NULL
, None
or your language's equivalent.
给定一个整数,判断是不是完美的幂指数,如果是就返回其中的一对m和k,其中m>1,k>1,并且m^k=n,如果不是则返回相应使用编程语言的空来代替,如Nothing
, Nil
, null
, NULL
, None
。
例子
isPerfectPower(4) => new int[]{2,2}
isPerfectPower(5) => null
isPerfectPower(8) => new int[]{2,3}
isPerfectPower(9) => new int[]{3,2}
特殊的说明:如果存在完美的幂指数有多对的话,则只要返回其中的一对即可,如81 = 3^4 = 9^2
,所以(3,4)和
(9,2)
是有效的解决方案
算法思想
对给定的整数进行开平方并取整,赋给变量s,循环从i=2开始遍历到i<s+1,其中声明变量k并赋值为2,while循环去判断i的k次幂是否等于给定的整数,不等则继续循环判断,否则直接返回相应的i和k
实现代码
public class PerfectPower {
public static int[] isPerfectPower(int n) {
int s=(int)Math.sqrt(n);
for(int i=2;i<s+1;i++){
int k=2;
while(Math.pow(i,k)<n)k+=1;
if(Math.pow(i,k)==n)return new int[]{i,k};
}
return null;
}
}