Print all integers that are sum of powers of two given numbers | Java implementation of the approach ; Function to print powerful integers ; Set is used to store distinct numbers in sorted order ; Store all the powers of y < bound in a vector to avoid calculating them again and again ; x ^ i ; If num is within limits insert it into the set ; Break out of the inner loop ; Adding any number to it will be out of bounds ; Increment i ; Print the contents of the set ; Driver code ; Print powerful integers
import java . util . * ; import java . lang . Math ; class GfG { static void powerfulIntegers ( int x , int y , int bound ) { Set < Integer > s = new HashSet < > ( ) ; ArrayList < Integer > powersOfY = new ArrayList < > ( ) ; int i ; powersOfY . add ( 1 ) ; for ( i = y ; i < bound && y != 1 ; i = i * y ) powersOfY . add ( i ) ; i = 0 ; while ( true ) { int xPowI = ( int ) Math . pow ( ( double ) x , ( double ) i ) ; for ( int j = 0 ; j < powersOfY . size ( ) ; ++ j ) { int num = xPowI + powersOfY . get ( j ) ; if ( num <= bound ) s . add ( num ) ; else break ; } if ( xPowI >= bound x == 1 ) break ; i ++ ; } Iterator itr = s . iterator ( ) ; while ( itr . hasNext ( ) ) { System . out . print ( itr . next ( ) + " ▁ " ) ; } } public static void main ( String [ ] args ) { int x = 2 , y = 1 , bound = 10 ; powerfulIntegers ( x , y , bound ) ; } }