[Codewars] 033: What's a Perfect Power anyway?

题目

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 mk = 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 mk = n as a proof. Otherwise return Nothing, Nil, null, NULL, None or your language's equivalent.

Note: For a perfect power, there might be several pairs. For example 81 = 3^4 = 9^2, so (3,4) and (9,2) are valid solutions. However, the tests take care of this, so if a number is a perfect power, return any pair that proves it.

Examples

isPP(4) => [2,2]
isPP(9) => [3,2]
isPP(5) => None

我的答案

import math
def isPP(n):
    for m in range(2, int(math.sqrt(n))+1):
        k = int(round(math.log(n, m)))
        if m ** k == n:
            return [m, k]
    return None
  • 慎用pow(a, b)函数进行开方运算,python3实测因为1/3(或1.0/3) = 0.3333333333333333,所以pow(216, 1/3) 和pow(216, 1.0/3)运行结果均为5.999999999999999,pow(216, 1/3) .is_integer()返回False。
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容