Check if a large number is divisible by a number which is a power of 2 | C ++ program for the above approach ; Function to check divisibility ; Calculate the number of digits in num ; Check if the length of the string is less than the powerOf2 then return false ; Check if the powerOf2 is 0 that means the given number is 1 and as every number is divisible by 1 so return true ; Find the number which is formed by the last n digits of the string where n = powerOf2 ; Check if the number formed is divisible by input num or not ; Driver Code ; Given number ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool checkIfDivisible ( string str , long long int num ) { long long int powerOf2 = log2 ( num ) ; if ( str . length ( ) < powerOf2 ) return false ; if ( powerOf2 == 0 ) return true ; long long int i , number = 0 ; int len = str . length ( ) ; for ( i = len - powerOf2 ; i < len ; i ++ ) { number += ( str [ i ] - '0' ) * pow ( 10 , powerOf2 - 1 ) ; powerOf2 -- ; } if ( number % num ) return false ; else return true ; } int main ( ) { string str = "213467756564" ; long long int num = 4 ; if ( checkIfDivisible ( str , num ) ) cout << " Yes " ; else cout << " No " ; return 0 ; }