Check if a number N can be expressed in base B | C ++ program for the above approach ; Function to check if a number N can be expressed in base B ; Check if n is greater than 0 ; Initialize a boolean variable ; Check if digit is 0 or 1 ; Subtract the appropriate power of B from it and increment higher digit ; Driver Code ; Given Number N and base B ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool check ( int n , int w ) { vector < int > a ( 105 ) ; int p = 0 ; while ( n > 0 ) { a [ p ++ ] = n % w ; n /= w ; } bool flag = true ; for ( int i = 0 ; i <= 100 ; i ++ ) { if ( a [ i ] == 0 a [ i ] == 1 ) continue ; else if ( a [ i ] == w a [ i ] == w - 1 ) a [ i + 1 ] ++ ; else flag = false ; } return flag ; } int main ( ) { int B = 3 , N = 7 ; if ( check ( N , B ) ) cout << " Yes " ; else cout << " No " ; return 0 ; }