Python 中的强大整数

pythonserver side programmingprogramming更新于 2025/7/16 11:24:17

假设我们有两个正整数 x 和 y,如果某个整数等于 x^i + y^j(其中 i >= 0 且 j >= 0),我们可以说该整数是强大的。我们必须找到一个值小于或等于界限的全能整数列表。

因此,如果输入为 x = 2 和 y = 3,界限为 10,则输出将为 [2,3,4,5,7,9,10],因为 2 = 2^0 + 3^0 3 = 2^1 + 3^0 4 = 2^0 + 3^1 5 = 2^1 + 3^1 7 = 2^2 + 3^1 9 = 2^3 + 3^0 10 = 2^0 + 3^2

为了解决这个问题,我们将遵循以下步骤 −

  • 将 a、b 初始化为 0
  • res:= a new list
  • 如果 x 等于 1 且 y 等于 1,则
    • 如果 bound>=2,则
      • 在 res 末尾插入 2
    • 否则当 x 等于 1 时,则
      • 当 y^b + 1 <= bound 时,执行
        • 将 y^b + 1 插入 res
        • b := b + 1
    • 否则当 y 等于 1 时,然后
      • 当 x^a + 1 <= bound 时,执行
        • 将 x^a + 1 插入 res
        • a := a + 1
    • 否则,
      • 当 x^a + 1<=bound 时,执行
        • 如果 x^a+y^b <= bound,则
          • b := b + 1
        • 否则,
          • a := a + 1
          • b:= 0

让我们看看下面的实现以便更好地理解 −

示例

class Solution:
   def powerfulIntegers(self, x, y, bound):
      a,b=0,0
      res=[]
      if x==1 and y==1:
         if bound>=2:
            res.append(2)
         elif x==1:
            while y**b+1<=bound:
               res.append(y**b+1)
               b+=1
         elif y==1:
            while x**a+1<=bound:
               res.append(x**a+1)
               a+=1
         else:
            while x**a+1<=bound:
               if x**a+y**b<=bound:
                  res.append(x**a+y**b)
                  b+=1
         else:
            a+=1
            b=0
      return list(set(res))
ob = Solution()
print(ob.powerfulIntegers(2,3,10))

输入

2,3,10

输出

[2, 3, 4, 5, 7, 9, 10]

相关文章


有用资源