Print all integers that are sum of powers of two given numbers | C ++ 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
#include <bits/stdc++.h> NEW_LINE using namespace std ; void powerfulIntegers ( int x , int y , int bound ) { set < int > s ; vector < int > powersOfY ; int i ; powersOfY . push_back ( 1 ) ; for ( i = y ; i < bound && y != 1 ; i = i * y ) powersOfY . push_back ( i ) ; i = 0 ; while ( true ) { int xPowI = pow ( x , i ) ; for ( auto j = powersOfY . begin ( ) ; j != powersOfY . end ( ) ; ++ j ) { int num = xPowI + * j ; if ( num <= bound ) s . insert ( num ) ; else break ; } if ( xPowI >= bound x == 1 ) break ; i ++ ; } set < int > :: iterator itr ; for ( itr = s . begin ( ) ; itr != s . end ( ) ; itr ++ ) { cout << * itr << " ▁ " ; } } int main ( ) { int x = 2 , y = 3 , bound = 10 ; powerfulIntegers ( x , y , bound ) ; return 0 ; }