Powerful Integers in Python


Suppose we have two positive integers x and y, we can say an integer is powerful if it is equal to x^i + y^j for some integers i >= 0 and j >= 0. We have to find a list of all-powerful integers that have value less than or equal to bound.

So, if the input is like x = 2 and y = 3 and the bound is 10, then the output will be [2,3,4,5,7,9,10], as 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

To solve this, we will follow these steps −

  • initialize a, b as 0
  • res:= a new list
  • if x is same as 1 and y is same as 1, then
    • if bound>=2, then
      • insert 2 at the end of res
    • otherwise when x is same as 1, then
      • while y^b + 1 <= bound, do
        • insert y^b + 1 into res
        • b := b + 1
    • otherwise when y is same as 1, then
      • while x^a + 1 <= bound, do
        • insert x^a + 1 into res
        • a := a + 1
    • otherwise,
      • while x^a + 1<=bound, do
        • if x^a+y^b <= bound, then
          • b := b + 1
        • otherwise,
          • a := a + 1
          • b:= 0

Let us see the following implementation to get better understanding −

Example

 Live Demo

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))

Input

2,3,10

Output

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

Updated on: 06-Jul-2020

157 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements