text
stringlengths
17
4.49k
code
stringlengths
49
5.46k
Sum of array elements possible by appending arr [ i ] / K to the end of the array K times for array elements divisible by K | C ++ program for the above approach ; Function to calculate sum of array elements after adding arr [ i ] / K to the end of the array if arr [ i ] is divisible by K ; Stores the sum of the array ; Stores the array elements ; Traverse the array ; Stores if the operation should be formed or not ; Traverse the vector V ; If flag is false and if v [ i ] is divisible by K ; Otherwise , set flag as true ; Increment the sum by v [ i % N ] ; Return the resultant sum ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int sum ( int arr [ ] , int N , int K ) { int sum = 0 ; vector < int > v ; for ( int i = 0 ; i < N ; i ++ ) { v . push_back ( arr [ i ] ) ; } bool flag = 0 ; for ( int i = 0 ; i < v . size ( ) ; i ++ ) { if ( ! flag && v [ i ] % K == 0 ) v . push_back ( v [ i ] / K ) ; else { flag = 1 ; } sum = sum + v [ i % N ] ; } return sum ; } int main ( ) { int arr [ ] = { 4 , 6 , 8 , 2 } ; int K = 2 ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << sum ( arr , N , K ) ; return 0 ; }
Count array elements whose count of divisors is a prime number | C ++ program for the above approach ; Function to count the array elements whose count of divisors is prime ; Stores the maximum element ; Find the maximum element ; Store if i - th element is prime ( 0 ) or non - prime ( 1 ) ; Base Case ; If i is a prime number ; Mark all multiples of i as non - prime ; Stores the count of divisors ; Base Case ; Iterate to count factors ; Stores the count of array elements whose count of divisors is a prime number ; Traverse the array arr [ ] ; If count of divisors is prime ; Return the resultant count ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int primeDivisors ( int arr [ ] , int N ) { int K = arr [ 0 ] ; for ( int i = 1 ; i < N ; i ++ ) { K = max ( K , arr [ i ] ) ; } int prime [ K + 1 ] = { 0 } ; prime [ 0 ] = 1 ; prime [ 1 ] = 1 ; for ( int i = 2 ; i < K + 1 ; i ++ ) { if ( ! prime [ i ] ) { for ( int j = 2 * i ; j < K + 1 ; j += i ) { prime [ j ] = 1 ; } } } int factor [ K + 1 ] = { 0 } ; factor [ 0 ] = 0 ; factor [ 1 ] = 1 ; for ( int i = 2 ; i < K + 1 ; i ++ ) { factor [ i ] += 1 ; for ( int j = i ; j < K + 1 ; j += i ) { factor [ j ] += 1 ; } } int count = 0 ; for ( int i = 0 ; i < N ; i ++ ) { if ( prime [ factor [ arr [ i ] ] ] == 0 ) count ++ ; } return count ; } int main ( ) { int arr [ ] = { 10 , 13 , 17 , 25 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << primeDivisors ( arr , N ) ; return 0 ; }
Count prime numbers up to N that can be represented as a sum of two prime numbers | C ++ program for the above approach ; Function to store all prime numbers up to N using Sieve of Eratosthenes ; Set 0 and 1 as non - prime ; If p is prime ; Set all multiples of p as non - prime ; Function to count prime numbers up to N that can be represented as the sum of two prime numbers ; Stores all the prime numbers ; Update the prime array ; Create a dp array of size n + 1 ; Update dp [ 1 ] = 0 ; Iterate over the range [ 2 , N ] ; Add the previous count value ; Increment dp [ i ] by 1 if i and ( i - 2 ) are both prime ; Print the result ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void SieveOfEratosthenes ( int n , bool prime [ ] ) { prime [ 0 ] = 0 ; prime [ 1 ] = 0 ; for ( int p = 2 ; p * p <= n ; p ++ ) { if ( prime [ p ] == true ) { for ( int i = p * p ; i <= n ; i += p ) { prime [ i ] = false ; } } } } void countPrime ( int n ) { bool prime [ n + 1 ] ; memset ( prime , true , sizeof ( prime ) ) ; SieveOfEratosthenes ( n , prime ) ; int dp [ n + 1 ] ; memset ( dp , 0 , sizeof ( dp ) ) ; dp [ 1 ] = 0 ; for ( int i = 2 ; i <= n ; i ++ ) { dp [ i ] += dp [ i - 1 ] ; if ( prime [ i ] == 1 && prime [ i - 2 ] == 1 ) { dp [ i ] ++ ; } } cout << dp [ n ] ; } int main ( ) { int N = 6 ; countPrime ( N ) ; return 0 ; }
Minimize sum of an array having Bitwise AND of all its pairs present in a given matrix | C ++ program of the above approach ; Function to find the minimum sum of the array such that Bitwise AND of arr [ i ] ana arr [ j ] is mat [ i ] [ j ] ; Stores the minimum possible sum ; Traverse the range [ 0 , N - 1 ] ; Stores the Bitwise OR of all the element of a row ; Traverse the range [ 0 , N - 1 ] ; If i not equal to j ; Update the value of res ; Increment the sum by res ; Return minimum possible sum ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int findMinSum ( vector < vector < int > > mat , int N ) { int sum = 0 ; for ( int i = 0 ; i < N ; i ++ ) { int res = 0 ; for ( int j = 0 ; j < N ; j ++ ) { if ( i != j ) { res |= mat [ i ] [ j ] ; } } sum += res ; } return sum ; } int main ( ) { vector < vector < int > > mat = { { -1 , 2 , 3 } , { 9 , -1 , 7 } , { 4 , 5 , -1 } } ; int N = mat . size ( ) ; cout << findMinSum ( mat , N ) ; return 0 ; }
LCM of unique elements present in an array | C ++ program for the above approach ; Function to find GCD of two numbers ; Base Case ; Recursively find the GCD ; Function to find LCM of two numbers ; Function to find LCM of unique elements present in the array ; Stores the frequency of each number of the array ; Store the frequency of each element of the array ; Store the required result ; Traverse the map freq ; If the frequency of the current element is 1 , then update ans ; If there is no unique element , set lcm to - 1 ; Print the result ; Driver Code ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; int findGCD ( int a , int b ) { if ( b == 0 ) return a ; return findGCD ( b , a % b ) ; } int findLCM ( int a , int b ) { return ( a * b ) / findGCD ( a , b ) ; } int uniqueElementsLCM ( int arr [ ] , int N ) { unordered_map < int , int > freq ; for ( int i = 0 ; i < N ; i ++ ) { freq [ arr [ i ] ] ++ ; } int lcm = 1 ; for ( auto i : freq ) { if ( i . second == 1 ) { lcm = findLCM ( lcm , i . first ) ; } } if ( lcm == 1 ) lcm = -1 ; cout << lcm ; } int main ( ) { int arr [ ] = { 1 , 2 , 1 , 3 , 3 , 4 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; uniqueElementsLCM ( arr , N ) ; return 0 ; }
Minimize maximum difference between adjacent elements possible by removing a single array element | C ++ Program to implement the above approach ; Function to find maximum difference between adjacent array elements ; Store the maximum difference ; Traverse the array ; Update maximum difference ; Function to calculate the minimum of maximum difference between adjacent array elements possible by removing a single array element ; Stores the required minimum ; Stores the updated array ; Skip the i - th element ; Update MinValue ; return MinValue ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int maxAdjacentDifference ( vector < int > A ) { int diff = 0 ; for ( int i = 1 ; i < ( int ) A . size ( ) ; i ++ ) { diff = max ( diff , A [ i ] - A [ i - 1 ] ) ; } return diff ; } int MinimumValue ( int arr [ ] , int N ) { int MinValue = INT_MAX ; for ( int i = 0 ; i < N ; i ++ ) { vector < int > new_arr ; for ( int j = 0 ; j < N ; j ++ ) { if ( i == j ) continue ; new_arr . push_back ( arr [ j ] ) ; } MinValue = min ( MinValue , maxAdjacentDifference ( new_arr ) ) ; } return MinValue ; } int main ( ) { int arr [ ] = { 1 , 3 , 7 , 8 } ; int N = sizeof ( arr ) / sizeof ( int ) ; cout << MinimumValue ( arr , N ) ; return 0 ; }
Number of Antisymmetric Relations on a set of N elements | C ++ program for the above approach ; Function to calculate the value of x ^ y % mod in O ( log y ) ; Stores the result of x ^ y ; Update x if it exceeds mod ; If y is odd , then multiply x with result ; Divide y by 2 ; Update the value of x ; Return the resultant value of x ^ y ; Function to count the number of antisymmetric relations in a set consisting of N elements ; Print the count of antisymmetric relations ; Driver Code
#include <iostream> NEW_LINE using namespace std ; const int mod = 1000000007 ; int power ( long long x , unsigned int y ) { int res = 1 ; x = x % mod ; while ( y > 0 ) { if ( y & 1 ) res = ( res * x ) % mod ; y = y >> 1 ; x = ( x * x ) % mod ; } return res ; } int antisymmetricRelation ( int N ) { return ( power ( 2 , N ) * 1LL * power ( 3 , ( N * N - N ) / 2 ) ) % mod ; } int main ( ) { int N = 2 ; cout << antisymmetricRelation ( N ) ; return 0 ; }
Number of Asymmetric Relations on a set of N elements | C ++ program for the above approach ; Function to calculate x ^ y modulo ( 10 ^ 9 + 7 ) ; Stores the result of x ^ y ; Update x if it exceeds mod ; If x is divisible by mod ; If y is odd , then multiply x with result ; Divide y by 2 ; Update the value of x ; Return the final value of x ^ y ; Function to count the number of asymmetric relations in a set consisting of N elements ; Return the resultant count ; Driver Code
#include <iostream> NEW_LINE using namespace std ; const int mod = 1000000007 ; int power ( long long x , unsigned int y ) { int res = 1 ; x = x % mod ; if ( x == 0 ) return 0 ; while ( y > 0 ) { if ( y & 1 ) res = ( res * x ) % mod ; y = y >> 1 ; x = ( x * x ) % mod ; } return res ; } int asymmetricRelation ( int N ) { return power ( 3 , ( N * N - N ) / 2 ) ; } int main ( ) { int N = 2 ; cout << asymmetricRelation ( N ) ; return 0 ; }
Check if two vectors are collinear or not | C ++ program for the above approach ; Function to calculate cross product of two vectors ; Update cross_P [ 0 ] ; Update cross_P [ 1 ] ; Update cross_P [ 2 ] ; Function to check if two given vectors are collinear or not ; Store the first and second vectors ; Store their cross product ; Calculate their cross product ; Check if their cross product is a NULL Vector or not ; Driver Code ; Given coordinates of the two vectors
#include <bits/stdc++.h> NEW_LINE using namespace std ; void crossProduct ( int vect_A [ ] , int vect_B [ ] , int cross_P [ ] ) { cross_P [ 0 ] = vect_A [ 1 ] * vect_B [ 2 ] - vect_A [ 2 ] * vect_B [ 1 ] ; cross_P [ 1 ] = vect_A [ 2 ] * vect_B [ 0 ] - vect_A [ 0 ] * vect_B [ 2 ] ; cross_P [ 2 ] = vect_A [ 0 ] * vect_B [ 1 ] - vect_A [ 1 ] * vect_B [ 0 ] ; } void checkCollinearity ( int x1 , int y1 , int z1 , int x2 , int y2 , int z2 ) { int A [ 3 ] = { x1 , y1 , z1 } ; int B [ 3 ] = { x2 , y2 , z2 } ; int cross_P [ 3 ] ; crossProduct ( A , B , cross_P ) ; if ( cross_P [ 0 ] == 0 && cross_P [ 1 ] == 0 && cross_P [ 2 ] == 0 ) cout << " Yes " ; else cout << " No " ; } int main ( ) { int x1 = 4 , y1 = 8 , z1 = 12 ; int x2 = 8 , y2 = 16 , z2 = 24 ; checkCollinearity ( x1 , y1 , z1 , x2 , y2 , z2 ) ; return 0 ; }
Program to calculate Kinetic Energy and Potential Energy | C ++ Program to implement the above approach ; Function to calculate Kinetic Energy ; Stores the Kinetic Energy ; Function to calculate Potential Energy ; Stores the Potential Energy ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; float kineticEnergy ( float M , float V ) { float KineticEnergy ; KineticEnergy = 0.5 * M * V * V ; return KineticEnergy ; } float potentialEnergy ( float M , float H ) { float PotentialEnergy ; PotentialEnergy = M * 9.8 * H ; return PotentialEnergy ; } int main ( ) { float M = 5.5 , H = 23.5 , V = 10.5 ; cout << " Kinetic ▁ Energy ▁ = ▁ " << kineticEnergy ( M , V ) << endl ; cout << " Potential ▁ Energy ▁ = ▁ " << potentialEnergy ( M , H ) << endl ; return 0 ; }
Count pairs with odd Bitwise XOR that can be removed and replaced by their Bitwise OR | C ++ program for the above approach ; Function to count the number of pairs required to be removed from the array and replaced by their Bitwise OR values ; Stores the count of even array elements ; Traverse the given array ; Increment the count of even array elements ; If the array contains at least one odd array element ; Otherwise , print 0 ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void countPairs ( int arr [ ] , int N ) { int even = 0 ; for ( int i = 0 ; i < N ; i ++ ) { if ( arr [ i ] % 2 == 0 ) even ++ ; } if ( N - even >= 1 ) { cout << even ; return ; } cout << 0 ; } int main ( ) { int arr [ ] = { 5 , 4 , 7 , 2 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; countPairs ( arr , N ) ; return 0 ; }
Distribute M objects starting from Sth person such that every ith person gets arr [ i ] objects | C ++ program for the above approach ; Function to find distribution of M objects among all array elements ; Stores the distribution of M objects ; Stores the indices of distribution ; Stores the remaining objects ; Iterate until rem is positive ; If the number of remaining objects exceeds required the number of objects ; Increase the number of objects for the index ptr by arr [ ptr ] ; Decrease remaining objects by arr [ ptr ] ; Increase the number of objects for the index ptr by rem ; Decrease remaining objects to 0 ; Increase ptr by 1 ; Print the final distribution ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void distribute ( int N , int K , int M , int arr [ ] ) { int distribution [ N ] = { 0 } ; int ptr = K - 1 ; int rem = M ; while ( rem > 0 ) { if ( rem >= arr [ ptr ] ) { distribution [ ptr ] += arr [ ptr ] ; rem -= arr [ ptr ] ; } else { distribution [ ptr ] += rem ; rem = 0 ; } ptr = ( ptr + 1 ) % N ; } for ( int i = 0 ; i < N ; i ++ ) { cout << distribution [ i ] << " ▁ " ; } } int main ( ) { int arr [ ] = { 2 , 3 , 2 , 1 , 4 } ; int M = 11 , S = 2 ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; distribute ( N , S , M , arr ) ; return 0 ; }
Sum of squares of differences between all pairs of an array | C ++ program for the above approach ; Function to calculate sum of squares of differences of all possible pairs ; Stores the final sum ; Stores temporary values ; Traverse the array ; Final sum ; Print the answer ; Driver Code ; Given array ; Size of the array ; Function call to find sum of square of differences of all possible pairs
#include <bits/stdc++.h> NEW_LINE using namespace std ; void sumOfSquaredDifferences ( int arr [ ] , int N ) { int ans = 0 ; int sumA = 0 , sumB = 0 ; for ( int i = 0 ; i < N ; i ++ ) { sumA += ( arr [ i ] * arr [ i ] ) ; sumB += arr [ i ] ; } sumA = N * sumA ; sumB = ( sumB * sumB ) ; ans = sumA - sumB ; cout << ans ; } int main ( ) { int arr [ ] = { 2 , 8 , 4 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; sumOfSquaredDifferences ( arr , N ) ; return 0 ; }
Count ways to remove objects such that exactly M equidistant objects remain | C ++ program for the above approach ; Function to count the number of ways of removing objects such that after removal , exactly M equidistant objects remain ; Store the resultant number of arrangements ; Base Case : When only 1 object is left ; Print the result and return ; Iterate until len <= n and increment the distance in each iteration ; Total length if adjacent objects are d distance apart ; If len > n ; Update the number of ways ; Print the result ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void waysToRemove ( int n , int m ) { int ans = 0 ; if ( m == 1 ) { cout << n ; return ; } for ( int d = 0 ; d >= 0 ; d ++ ) { int len = m + ( m - 1 ) * d ; if ( len > n ) break ; ans += ( n - len ) + 1 ; } cout << ans ; } int main ( ) { int N = 5 , M = 3 ; waysToRemove ( N , M ) ; return 0 ; }
Count unique stairs that can be reached by moving given number of steps forward or backward | C ++ program for the above approach ; Function to count the number of unique stairs visited ; Checks whether the current stair is visited or not ; Store the possible moves from the current position ; Initialize a queue ; / Push the starting position ; Mark the starting position S as visited ; Iterate until queue is not empty ; Store the current stair number ; Pop it from the queue ; Check for all possible moves from the current stair ; Store the new stair number ; If it is valid and unvisited ; Push it into queue ; Mark the stair as visited ; Store the result ; Count the all visited stairs ; Print the result ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void countStairs ( int n , int x , int a , int b ) { int vis [ n + 1 ] = { 0 } ; int moves [ ] = { + a , - a , + b , - b } ; queue < int > q ; q . push ( x ) ; vis [ x ] = 1 ; while ( ! q . empty ( ) ) { int currentStair = q . front ( ) ; q . pop ( ) ; for ( int j = 0 ; j < 4 ; j ++ ) { int newStair = currentStair + moves [ j ] ; if ( newStair > 0 && newStair <= n && ! vis [ newStair ] ) { q . push ( newStair ) ; vis [ newStair ] = 1 ; } } } int cnt = 0 ; for ( int i = 1 ; i <= n ; i ++ ) if ( vis [ i ] == 1 ) cnt ++ ; cout << cnt ; } int main ( ) { int N = 10 , S = 2 , A = 5 , B = 7 ; countStairs ( N , S , A , B ) ; return 0 ; }
Count smaller elements present in the array for each array element | C ++ program for the above approach ; Function to count for each array element , the number of elements that are smaller than that element ; Traverse the array ; Stores the count ; Traverse the array ; Increment count ; Print the count of smaller elements for the current element ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void smallerNumbers ( int arr [ ] , int N ) { for ( int i = 0 ; i < N ; i ++ ) { int count = 0 ; for ( int j = 0 ; j < N ; j ++ ) { if ( arr [ j ] < arr [ i ] ) { count ++ ; } } cout << count << " ▁ " ; } } int main ( ) { int arr [ ] = { 3 , 4 , 1 , 1 , 2 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; smallerNumbers ( arr , N ) ; return 0 ; }
Minimize divisions by 2 , 3 , or 5 required to make two given integers equal | C ++ program for the above approach ; Function to calculate GCD of two numbers ; Base Case ; Calculate GCD recursively ; Function to count the minimum number of divisions required to make X and Y equal ; Calculate GCD of X and Y ; Divide X and Y by their GCD ; Stores the number of divisions ; Iterate until X != Y ; Maintain the order X <= Y ; If X is divisible by 2 , then divide X by 2 ; If X is divisible by 3 , then divide X by 3 ; If X is divisible by 5 , then divide X by 5 ; If X is not divisible by 2 , 3 , or 5 , then print - 1 ; Increment count by 1 ; Print the value of count as the minimum number of operations ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int gcd ( int a , int b ) { if ( b == 0 ) { return a ; } return gcd ( b , a % b ) ; } void minimumOperations ( int X , int Y ) { int GCD = gcd ( X , Y ) ; X = X / GCD ; Y = Y / GCD ; int count = 0 ; while ( X != Y ) { if ( Y > X ) { swap ( X , Y ) ; } if ( X % 2 == 0 ) { X = X / 2 ; } else if ( X % 3 == 0 ) { X = X / 3 ; } else if ( X % 5 == 0 ) { X = X / 5 ; } else { cout << " - 1" ; return ; } count ++ ; } cout << count ; } int main ( ) { int X = 15 , Y = 20 ; minimumOperations ( X , Y ) ; return 0 ; }
Minimum increments or decrements required to convert a sorted array into a power sequence | C ++ program for the above approach ; Function to find the minimum number of increments or decrements required to convert array into a power sequence ; Initialize the count to f ( X ) for X = 1 ; Calculate the value of f ( X ) X ^ ( n - 1 ) <= f ( 1 ) + a [ n - 1 ] ; Calculate F ( x ) ; Check if X ^ ( n - 1 ) > f ( 1 ) + a [ n - 1 ] ; Update ans to store the minimum of ans and F ( x ) ; Return the minimum number of operations required ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int minOperations ( int a [ ] , int n ) { int ans = accumulate ( a , a + n , 0 ) - n ; for ( int x = 1 ; ; x ++ ) { int curPow = 1 , curCost = 0 ; for ( int i = 0 ; i < n ; i ++ ) { curCost += abs ( a [ i ] - curPow ) ; curPow *= x ; } if ( curPow / x > ans + a [ n - 1 ] ) break ; ans = min ( ans , curCost ) ; } return ans ; } int main ( ) { int arr [ ] = { 1 , 5 , 7 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << minOperations ( arr , N ) ; return 0 ; }
Modulo Operations in Programming With Negative Results | C ++ program to illustrate modulo operations using the above equation ; Function to calculate and return the remainder of a % n ; Type casting is necessary as ( int ) / ( int ) will give int result , i . e . - 3 / 2 will give - 1 and not - 1.5 ; Return the resultant remainder ; Driver Code ; Modulo of two positive numbers ; Modulo of a negative number by a positive number ; Modulo of a positive number by a negative number ; Modulo of two negative numbers
#include <bits/stdc++.h> NEW_LINE using namespace std ; int floorMod ( int a , int n ) { int q = ( int ) floor ( ( double ) a / n ) ; return a - n * q ; } int main ( ) { int a , b ; a = 9 ; b = 4 ; cout << a << " ▁ % ▁ " << b << " ▁ = ▁ " << floorMod ( a , b ) << " STRNEWLINE " ; a = -9 ; b = 4 ; cout << a << " ▁ % ▁ " << b << " ▁ = ▁ " << floorMod ( a , b ) << " STRNEWLINE " ; a = 9 ; b = -4 ; cout << a << " ▁ % ▁ " << b << " ▁ = ▁ " << floorMod ( a , b ) << " STRNEWLINE " ; a = -9 ; b = -4 ; cout << a << " ▁ % ▁ " << b << " ▁ = ▁ " << floorMod ( a , b ) << " STRNEWLINE " ; return 0 ; }
Find the absolute difference between the nearest powers of two given integers for every array element | C ++ program for the above approach ; Function to print the array ; Traverse the array ; Function to modify array elements by absolute difference of the nearest perfect power of a and b ; Traverse the array arr [ ] ; Find the log a of arr [ i ] ; Find the power of a less than and greater than a ; Find the log b of arr [ i ] ; Find the power of b less than and greater than b ; Update arr [ i ] with absolute difference of log_a & log _b ; Print the modified array ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void printArray ( int arr [ ] , int N ) { for ( int i = 0 ; i < N ; i ++ ) { cout << arr [ i ] << " ▁ " ; } } void nearestPowerDiff ( int arr [ ] , int N , int a , int b ) { for ( int i = 0 ; i < N ; i ++ ) { int log_a = log ( arr [ i ] ) / log ( a ) ; int A = pow ( a , log_a ) ; int B = pow ( a , log_a + 1 ) ; if ( ( arr [ i ] - A ) < ( B - arr [ i ] ) ) log_a = A ; else log_a = B ; int log_b = log ( arr [ i ] ) / log ( b ) ; A = pow ( b , log_b ) ; B = pow ( b , log_b + 1 ) ; if ( ( arr [ i ] - A ) < ( B - arr [ i ] ) ) log_b = A ; else log_b = B ; arr [ i ] = abs ( log_a - log_b ) ; } printArray ( arr , N ) ; } int main ( ) { int arr [ ] = { 5 , 12 , 25 } ; int A = 2 , B = 3 ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; nearestPowerDiff ( arr , N , A , B ) ; return 0 ; }
Count subarrays having even Bitwise OR | C ++ program for the above approach ; Function to count the number of subarrays having even Bitwise OR ; Store number of subarrays having even bitwise OR ; Store the length of the current subarray having even numbers ; Traverse the array ; If the element is even ; Increment size of the current continuous sequence of even array elements ; If arr [ i ] is odd ; If length is non zero ; Adding contribution of subarrays consisting only of even numbers ; Make length of subarray as 0 ; Add contribution of previous subarray ; Return total count of subarrays ; Driver Code ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; int bitOr ( int arr [ ] , int N ) { int count = 0 ; int length = 0 ; for ( int i = 0 ; i < N ; i ++ ) { if ( arr [ i ] % 2 == 0 ) { length ++ ; } else { if ( length != 0 ) { count += ( ( length ) * ( length + 1 ) ) / 2 ; } length = 0 ; } } count += ( ( length ) * ( length + 1 ) ) / 2 ; return count ; } int main ( ) { int arr [ ] = { 1 , 5 , 4 , 2 , 6 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << bitOr ( arr , N ) ; return 0 ; }
Generate an array having sum of Bitwise OR of same | C ++ program for the above approach ; Function to print the resultant array ; Stores the sum of the array ; Calculate sum of the array ; If sum > K ; Not possible to construct the array ; Update K ; Stores the resultant array ; Traverse the array ; Stores the current element ; If jth bit is not set and value of 2 ^ j is less than K ; Update curr ; Update K ; Push curr into B ; If K is greater than 0 ; Print the vector B ; Otherwise ; Driver Code ; Input ; Size of the array ; Given input ; Function call to print the required array
#include <bits/stdc++.h> NEW_LINE using namespace std ; void constructArr ( int A [ ] , int N , int K ) { int sum = 0 ; for ( int i = 0 ; i < N ; i ++ ) { sum += A [ i ] ; } if ( sum > K ) { cout << -1 << " STRNEWLINE " ; return ; } K -= sum ; vector < int > B ; for ( int i = 0 ; i < N ; i ++ ) { int curr = A [ i ] ; for ( int j = 32 ; j >= 0 and K ; j -- ) { if ( ( curr & ( 1LL << j ) ) == 0 and ( 1LL << j ) <= K ) { curr |= ( 1LL << j ) ; K -= ( 1LL << j ) ; } } B . push_back ( curr ) ; } if ( ! K ) { for ( auto it : B ) { cout << it << " ▁ " ; } cout << " STRNEWLINE " ; } else { cout << " - 1" << " STRNEWLINE " ; } } int main ( ) { int arr [ ] = { 1 , 2 , 3 , 4 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; int K = 32 ; constructArr ( arr , N , K ) ; }
Find all pairs raised to power K differs by exactly N | C ++ program for the above approach ; Function to print pairs whose difference raised to the power K is X ; Stores the count of valid pairs ; Iterate over the range [ - 1000 , 1000 ] ; Iterate over the range [ - 1000 , 1000 ] ; If the current pair satisfies the given condition ; Increment the count by 1 ; If no such pair exists ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void ValidPairs ( int X , int K ) { long long int count = 0 ; for ( int A = -1000 ; A <= 1000 ; A ++ ) { for ( int B = -1000 ; B <= 1000 ; B ++ ) { if ( pow ( A , K ) - pow ( B , K ) == X ) { count ++ ; cout << A << " ▁ " << B << endl ; } } } if ( count == 0 ) { cout << " - 1" ; } } int main ( ) { long long int X = 33 ; int K = 5 ; ValidPairs ( X , K ) ; return 0 ; }
Connect a graph by M edges such that the graph does not contain any cycle and Bitwise AND of connected vertices is maximum | C ++ program for the above approach ; Function to find the maximum Bitwise AND of connected components possible by connecting a graph using M edges ; Stores total number of ways to connect the graph ; Stores the maximum Bitwise AND ; Iterate over the range [ 0 , 2 ^ n ] ; Store the Bitwise AND of the connected vertices ; Store the count of the connected vertices ; Check for all the bits ; If i - th bit is set ; If the first vertex is added ; Set andans equal to arr [ i ] ; Calculate Bitwise AND of arr [ i ] with andans ; Increase the count of connected vertices ; If number of connected vertices is ( m + 1 ) , no cycle is formed ; Find the maximum Bitwise AND value possible ; Return the maximum Bitwise AND possible ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int maximumAND ( int arr [ ] , int n , int m ) { int tot = 1 << n ; int mx = 0 ; for ( int bm = 0 ; bm < tot ; bm ++ ) { int andans = 0 ; int count = 0 ; for ( int i = 0 ; i < n ; ++ i ) { if ( ( bm >> i ) & 1 ) { if ( count == 0 ) { andans = arr [ i ] ; } else { andans = andans & arr [ i ] ; } count ++ ; } } if ( count == ( m + 1 ) ) { mx = max ( mx , andans ) ; } } return mx ; } int main ( ) { int arr [ ] = { 1 , 2 , 3 , 4 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; int M = 2 ; cout << maximumAND ( arr , N , M ) ; return 0 ; }
Calculate sum of the array generated by given operations | C ++ program for the above approach ; Function to find the sum of the array formed by performing given set of operations while traversing the array ops [ ] ; If the size of array is 0 ; Stores the required sum ; Traverse the array ops [ ] ; If the character is C , remove the top element from the stack ; If the character is D , then push 2 * top element into stack ; If the character is + , add sum of top two elements from the stack ; Otherwise , push x and add it to ans ; Print the resultant sum ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void findTotalSum ( vector < string > & ops ) { if ( ops . empty ( ) ) { cout << 0 ; return ; } stack < int > pts ; int ans = 0 ; for ( int i = 0 ; i < ops . size ( ) ; i ++ ) { if ( ops [ i ] == " C " ) { ans -= pts . top ( ) ; pts . pop ( ) ; } else if ( ops [ i ] == " D " ) { pts . push ( pts . top ( ) * 2 ) ; ans += pts . top ( ) ; } else if ( ops [ i ] == " + " ) { int a = pts . top ( ) ; pts . pop ( ) ; int b = pts . top ( ) ; pts . push ( a ) ; ans += ( a + b ) ; pts . push ( a + b ) ; } else { int n = stoi ( ops [ i ] ) ; ans += n ; pts . push ( n ) ; } } cout << ans ; } int main ( ) { vector < string > arr = { "5" , " - 2" , " C " , " D " , " + " } ; findTotalSum ( arr ) ; return 0 ; }
XOR of major diagonal elements of a 3D Matrix | C ++ program for the above approach ; Function to calculate Bitwise XOR of major diagonal elements of 3D matrix ; Stores the Bitwise XOR of the major diagonal elements ; If element is part of major diagonal ; Print the resultant Bitwise XOR ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void findXOR ( vector < vector < vector < int > > > & mat , int N ) { int XOR = 0 ; for ( int i = 0 ; i < N ; i ++ ) { for ( int j = 0 ; j < N ; j ++ ) { for ( int k = 0 ; k < N ; k ++ ) { if ( ( i == j && j == k ) ) { XOR ^= mat [ i ] [ j ] [ k ] ; XOR ^= mat [ i ] [ j ] [ N - k - 1 ] ; } } } } cout << XOR << " STRNEWLINE " ; } int main ( ) { vector < vector < vector < int > > > mat = { { { 1 , 2 } , { 3 , 4 } } , { { 5 , 6 } , { 7 , 8 } } } ; int N = mat . size ( ) ; findXOR ( mat , N ) ; return 0 ; }
XOR of major diagonal elements of a 3D Matrix | C ++ program for the above approach ; Function to find the Bitwise XOR of both diagonal elements of 3D matrix ; Stores the Bitwise XOR of the major diagonal elements ; Print the resultant Bitwise XOR ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void findXOR ( vector < vector < vector < int > > > & mat , int N ) { int XOR = 0 ; for ( int i = 0 ; i < N ; i ++ ) { XOR ^= mat [ i ] [ i ] [ i ] ; XOR ^= mat [ i ] [ i ] [ N - i - 1 ] ; } cout << XOR << " STRNEWLINE " ; } int main ( ) { vector < vector < vector < int > > > mat = { { { 1 , 2 } , { 3 , 4 } } , { { 5 , 6 } , { 7 , 8 } } } ; int N = mat . size ( ) ; findXOR ( mat , N ) ; return 0 ; }
Count of subtrees possible from an N | C ++ program of the above approach ; Adjacency list to represent the graph ; Stores the count of subtrees possible from given N - ary Tree ; Utility function to count the number of subtrees possible from given N - ary Tree ; Stores the count of subtrees when cur node is the root ; Traverse the adjacency list ; Iterate over every ancestor ; Calculate product of the number of subtrees for each child node ; Update the value of ans ; Return the resultant count ; Function to count the number of subtrees in the given tree ; Initialize an adjacency matrix ; Add the edges ; Function Call to count the number of subtrees possible ; Print count of subtrees ; Driver Code
#include <bits/stdc++.h> NEW_LINE #define MAX 300004 NEW_LINE using namespace std ; vector < int > graph [ MAX ] ; int mod = 1e9 + 7 ; int ans = 0 ; int countSubtreesUtil ( int cur , int par ) { int res = 1 ; for ( int i = 0 ; i < graph [ cur ] . size ( ) ; i ++ ) { int v = graph [ cur ] [ i ] ; if ( v == par ) continue ; res = ( res * ( countSubtreesUtil ( v , cur ) + 1 ) ) % mod ; } ans = ( ans + res ) % mod ; return res ; } void countSubtrees ( int N , vector < pair < int , int > > & adj ) { for ( int i = 0 ; i < N - 1 ; i ++ ) { int a = adj [ i ] . first ; int b = adj [ i ] . second ; graph [ a ] . push_back ( b ) ; graph [ b ] . push_back ( a ) ; } countSubtreesUtil ( 1 , 1 ) ; cout << ans + 1 ; } int main ( ) { int N = 3 ; vector < pair < int , int > > adj = { { 0 , 1 } , { 1 , 2 } } ; countSubtrees ( N , adj ) ; return 0 ; }
Find the player who wins the game of placing alternate + and | C ++ program for the above approach ; Function to check which player wins the game ; Stores the difference between + ve and - ve array elements ; Traverse the array ; Update diff ; Checks if diff is even ; Driver Code ; Given Input ; Function call to check which player wins the game
#include <bits/stdc++.h> NEW_LINE using namespace std ; void checkWinner ( int arr [ ] , int N ) { int diff = 0 ; for ( int i = 0 ; i < N ; i ++ ) { diff -= arr [ i ] ; } if ( diff % 2 == 0 ) { cout << " A " ; } else { cout << " B " ; } } int main ( ) { int arr [ ] = { 1 , 2 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; checkWinner ( arr , N ) ; return 0 ; }
Generate an array having sum of Euler Totient Function of all elements equal to N | C ++ program for the above approach ; Function to construct the array such the sum of values of Euler Totient functions of all array elements is N ; Stores the resultant array ; Find divisors in sqrt ( N ) ; If N is divisible by i ; Push the current divisor ; If N is not a perfect square ; Push the second divisor ; Print the resultant array ; Driver Code ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; void constructArray ( int N ) { vector < int > ans ; for ( int i = 1 ; i * i <= N ; i ++ ) { if ( N % i == 0 ) { ans . push_back ( i ) ; if ( N != ( i * i ) ) { ans . push_back ( N / i ) ; } } } for ( auto it : ans ) { cout << it << " ▁ " ; } } int main ( ) { int N = 12 ; constructArray ( N ) ; return 0 ; }
Place N boys and M girls in different rows such that count of persons placed in each row is maximized | C ++ Program to implement the above approach ; Function to calculate GCD of two numbers ; Function to count maximum persons that can be placed in a row ; Driver Code ; Input ; Function to count maximum persons that can be placed in a row
#include <bits/stdc++.h> NEW_LINE using namespace std ; int gcd ( int a , int b ) { if ( b == 0 ) return a ; return gcd ( b , a % b ) ; } int maximumRowValue ( int n , int m ) { return gcd ( n , m ) ; } int main ( ) { int N = 4 ; int M = 2 ; cout << maximumRowValue ( N , M ) ; }
Program to generate an array having convolution of two given arrays | C ++ program for the above approach ; Function to generate a convolution array of two given arrays ; Stores the size of arrays ; Stores the final array ; Traverse the two given arrays ; Update the convolution array ; Print the convolution array c [ ] ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; constexpr int MOD = 998244353 ; void findConvolution ( const vector < int > & a , const vector < int > & b ) { int n = a . size ( ) , m = b . size ( ) ; vector < long long > c ( n + m - 1 ) ; for ( int i = 0 ; i < n ; ++ i ) { for ( int j = 0 ; j < m ; ++ j ) { c [ i + j ] += 1LL * ( a [ i ] * b [ j ] ) % MOD ; } } for ( int k = 0 ; k < c . size ( ) ; ++ k ) { c [ k ] %= MOD ; cout << c [ k ] << " ▁ " ; } } int main ( ) { vector < int > A = { 1 , 2 , 3 , 4 } ; vector < int > B = { 5 , 6 , 7 , 8 , 9 } ; findConvolution ( A , B ) ; return 0 ; }
Minimum number of 1 s present in a submatrix of given dimensions in a Binary Matrix | C ++ program for the above approach ; Function to count number of 1 s present in a sub matrix from ( start_i , start_j ) to ( end_i , end_j ) ; Stores the number of 1 s present in current submatrix ; Traverse the submatrix ; If mat [ x ] [ y ] is equal to 1 ; Increase count by 1 ; Return the total count of 1 s ; Function to find the minimum number of 1 s present in a sub - matrix of size A * B or B * A ; Stores the minimum count of 1 s ; Iterate i from 0 to N ; Iterate j from 0 to M ; If a valid sub matrix of size A * B from ( i , j ) is possible ; Count the number of 1 s present in the sub matrix of size A * B from ( i , j ) ; Update minimum if count is less than the current minimum ; If a valid sub matrix of size B * A from ( i , j ) is possible ; Count the number of 1 s in the sub matrix of size B * A from ( i , j ) ; Update minimum if count is less than the current minimum ; Return minimum as the final result ; Driver Code ; Given Input ; Function call to find the minimum number of 1 s in a submatrix of size A * B or B * A
#include <bits/stdc++.h> NEW_LINE using namespace std ; #define P 51 NEW_LINE int count1s ( int start_i , int start_j , int end_i , int end_j , int mat [ ] [ P ] ) { int count = 0 ; for ( int x = start_i ; x < end_i ; x ++ ) { for ( int y = start_j ; y < end_j ; y ++ ) { if ( mat [ x ] [ y ] == 1 ) count ++ ; } } return count ; } int findMinimumCount ( int N , int M , int A , int B , int mat [ ] [ P ] ) { int minimum = 1e9 ; for ( int i = 0 ; i < N ; i ++ ) { for ( int j = 0 ; j < M ; j ++ ) { if ( i + A <= N && j + B <= M ) { int count = count1s ( i , j , i + A , j + B , mat ) ; minimum = min ( count , minimum ) ; } if ( i + B <= N && j + A <= M ) { int count = count1s ( i , j , i + B , j + A , mat ) ; minimum = min ( count , minimum ) ; } } } return minimum ; } int main ( ) { int A = 2 , B = 2 ; int N = 3 , M = 4 ; int mat [ P ] [ P ] = { { 1 , 0 , 1 , 0 } , { 0 , 1 , 0 , 1 } , { 1 , 0 , 1 , 0 } } ; cout << findMinimumCount ( N , M , A , B , mat ) ; }
Program to check if a number can be expressed as an even power of 2 or not | C ++ program for the above approach ; Function to check if N can be expressed as an even power of 2 ; Iterate till x is N ; if x is even then return true ; Increment x ; If N is not a power of 2 ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool checkEvenPower ( int n ) { int x = 0 ; while ( x < n ) { int value = pow ( 2 , x ) ; if ( value == n ) { if ( x % 2 == 0 ) return true ; else return false ; } x ++ ; } return false ; } int main ( ) { int N = 4 ; cout << ( checkEvenPower ( N ) ? " Yes " : " No " ) ; }
Program to check if a number can be expressed as an even power of 2 or not | C ++ program for the above approach ; Function to check if N can be expressed as an even power of 2 or not ; Iterate until low > high ; Calculate mid ; If 2 ^ mid is equal to n ; If mid is odd ; Update the value of low ; Update the value of high ; Otherwise ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; string checkEvenPower ( int n ) { int low = 0 , high = n ; while ( low <= high ) { int mid = low + ( high - low ) / 2 ; int value = pow ( 2 , mid ) ; if ( value == n ) { if ( mid % 2 == 1 ) return " No " ; else return " Yes " ; } else if ( value < n ) low = mid + 1 ; else high = mid - 1 ; } return " No " ; } int main ( ) { int N = 4 ; cout << checkEvenPower ( N ) ; return 0 ; }
Program to check if a number can be expressed as an even power of 2 or not | C ++ program for the above approach ; Function to check if N can be expressed as an even power of 2 or not ; If N is not a power of 2 ; Bitwise AND operation ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool checkEvenPower ( long long int N ) { if ( ( N & ( N - 1 ) ) != 0 ) return false ; N = N & 0x55555555 ; return ( N > 0 ) ; } int main ( ) { int N = 4 ; cout << checkEvenPower ( N ) ; return 0 ; }
Sum of quotients of division of N by powers of K not exceeding N | C ++ program for the above approach ; Function to calculate sum of quotients obtained by dividing N by powers of K <= N ; Store the required sum ; Iterate until i exceeds N ; Update sum ; Multiply i by K to obtain next power of K ; Print the result ; Driver Code ; Given N and K
#include <bits/stdc++.h> NEW_LINE using namespace std ; int findSum ( int N , int K ) { int ans = 0 ; int i = 1 ; while ( i <= N ) { ans += N / i ; i = i * K ; } cout << ans ; } int main ( ) { int N = 10 , K = 2 ; findSum ( N , K ) ; return 0 ; }
Count Arithmetic Progressions having sum S and common difference equal to D | C ++ program for the above approach ; Function to count the number of APs with sum S and common difference D ; Multiply S by 2 ; Stores the count of APs ; Iterate over the factors of 2 * S ; Check if i is the factor or not ; Conditions to check if AP can be formed using factor F ; Return the total count of APs ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int countAPs ( int S , int D ) { S = S * 2 ; int answer = 0 ; for ( int i = 1 ; i <= sqrt ( S ) ; i ++ ) { if ( S % i == 0 ) { if ( ( ( S / i ) - D * i + D ) % 2 == 0 ) answer ++ ; if ( ( D * i - ( S / i ) + D ) % 2 == 0 ) answer ++ ; } } return answer ; } int main ( ) { int S = 12 , D = 1 ; cout << countAPs ( S , D ) ; return 0 ; }
Minimize insertions to make sum of every pair of consecutive array elements at most K | C ++ program for the above approach ; Function to count minimum number of insertions required to make sum of every pair of adjacent elements at most K ; Stores if it is possible to make sum of each pair of adjacent elements at most K ; Stores the count of insertions ; Stores the previous value to index i ; Traverse the array ; If arr [ i ] is greater than or equal to K ; Mark possible 0 ; If last + arr [ i ] is greater than K ; Increment res by 1 ; Assign arr [ i ] to last ; If possible to make the sum of pairs of adjacent elements at most K ; Otherwise print " - 1" ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void minimumInsertions ( int arr [ ] , int N , int K ) { bool possible = 1 ; int res = 0 ; int last = 0 ; for ( int i = 0 ; i < N ; i ++ ) { if ( arr [ i ] >= K ) { possible = 0 ; break ; } if ( last + arr [ i ] > K ) res ++ ; last = arr [ i ] ; } if ( possible ) { cout << res ; } else { cout << " - 1" ; } } int main ( ) { int arr [ ] = { 1 , 2 , 3 , 4 , 5 } ; int K = 6 ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; minimumInsertions ( arr , N , K ) ; return 0 ; }
Maximum sum of K | C ++ program for the above approach ; Function to count the number of distinct elements present in the array ; Insert all elements into the Set ; Return the size of set ; Function that finds the maximum sum of K - length subarray having same unique elements as arr [ ] ; Not possible to find a subarray of size K ; Initialize Set ; Calculate sum of the distinct elements ; If the set size is same as the count of distinct elements ; Update the maximum value ; Driver code ; Stores the count of distinct elements
#include <bits/stdc++.h> NEW_LINE using namespace std ; int distinct ( int arr [ ] , int n ) { map < int , int > mpp ; for ( int i = 0 ; i < n ; i ++ ) { mpp [ arr [ i ] ] = 1 ; } return mpp . size ( ) ; } int maxSubSum ( int arr [ ] , int n , int k , int totalDistinct ) { if ( k > n ) return 0 ; int maxm = 0 , sum = 0 ; for ( int i = 0 ; i < n - k + 1 ; i ++ ) { sum = 0 ; set < int > st ; for ( int j = i ; j < i + k ; j ++ ) { sum += arr [ j ] ; st . insert ( arr [ j ] ) ; } if ( ( int ) st . size ( ) == totalDistinct ) maxm = max ( sum , maxm ) ; } return maxm ; } int main ( ) { int arr [ ] = { 7 , 7 , 2 , 4 , 2 , 7 , 4 , 6 , 6 , 6 } ; int K = 6 ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; int totalDistinct = distinct ( arr , N ) ; cout << ( maxSubSum ( arr , N , K , totalDistinct ) ) ; return 0 ; }
Maximum sum of K | C ++ program for the above approach ; Function to count the number of distinct elements present in the array ; Insert array elements into set ; Return the st size ; Function to calculate maximum sum of K - length subarray having same unique elements as arr [ ] ; Not possible to find an subarray of length K from an N - sized array , if K > N ; Traverse the array ; Update the mp ; If i >= K , then decrement arr [ i - K ] element 's one occurence ; If frequency of any element is 0 then remove the element ; If mp size is same as the count of distinct elements of array arr [ ] then update maximum sum ; Function that finds the maximum sum of K - length subarray having same number of distinct elements as the original array ; Size of array ; Stores count of distinct elements ; Print maximum subarray sum ; Driver Code ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; int distinct ( vector < int > arr , int N ) { set < int > st ; for ( int i = 0 ; i < N ; i ++ ) { st . insert ( arr [ i ] ) ; } return st . size ( ) ; } int maxSubarraySumUtil ( vector < int > arr , int N , int K , int totalDistinct ) { if ( K > N ) return 0 ; int mx = 0 ; int sum = 0 ; map < int , int > mp ; for ( int i = 0 ; i < N ; i ++ ) { mp [ arr [ i ] ] += 1 ; sum += arr [ i ] ; if ( i >= K ) { mp [ arr [ i - K ] ] -= 1 ; sum -= arr [ i - K ] ; if ( mp [ arr [ i - K ] ] == 0 ) mp . erase ( arr [ i - K ] ) ; } if ( mp . size ( ) == totalDistinct ) mx = max ( mx , sum ) ; } return mx ; } void maxSubarraySum ( vector < int > arr , int K ) { int N = arr . size ( ) ; int totalDistinct = distinct ( arr , N ) ; cout << maxSubarraySumUtil ( arr , N , K , totalDistinct ) ; } int main ( ) { vector < int > arr { 7 , 7 , 2 , 4 , 2 , 7 , 4 , 6 , 6 , 6 } ; int K = 6 ; maxSubarraySum ( arr , K ) ; }
Number of Irreflexive Relations on a Set | C ++ program for the above approach ; Function to calculate x ^ y modulo 1000000007 in O ( log y ) ; Stores the result of x ^ y ; Update x if it exceeds mod ; If x is divisible by mod ; If y is odd , then multiply x with result ; Divide y by 2 ; Update the value of x ; Return the resultant value of x ^ y ; Function to count the number of irreflixive relations in a set consisting of N elements ; Return the resultant count ; Driver Code
#include <iostream> NEW_LINE using namespace std ; const int mod = 1000000007 ; int power ( long long x , unsigned int y ) { int res = 1 ; x = x % mod ; if ( x == 0 ) return 0 ; while ( y > 0 ) { if ( y & 1 ) res = ( res * x ) % mod ; y = y >> 1 ; x = ( x * x ) % mod ; } return res ; } int irreflexiveRelation ( int N ) { return power ( 2 , N * N - N ) ; } int main ( ) { int N = 2 ; cout << irreflexiveRelation ( N ) ; return 0 ; }
Count Arithmetic Progressions having sum N and common difference equal to 1 | C ++ program for the above approach ; Function to count all possible AP series with common difference 1 and sum of elements equal to N ; Stores the count of AP series ; Traverse through all factors of 2 * N ; Check for the given conditions ; Increment count ; Print count - 1 ; Driver Code ; Given value of N ; Function call to count required number of AP series
#include <bits/stdc++.h> NEW_LINE using namespace std ; void countAPs ( long long int N ) { long long int count = 0 ; for ( long long int i = 1 ; i * i <= 2 * N ; i ++ ) { long long int res = 2 * N ; if ( res % i == 0 ) { long long int op = res / i - i + 1 ; if ( op % 2 == 0 ) { count ++ ; } if ( i * i != res and ( i - res / i + 1 ) % 2 == 0 ) { count ++ ; } } } cout << count - 1 << " STRNEWLINE " ; } int main ( ) { long long int N = 963761198400 ; countAPs ( N ) ; }
Check if concatenation of first and last digits forms a prime number or not for each array element | C ++ program for the above approach ; Stores if i is prime ( 1 ) or non - prime ( 0 ) ; Function to build sieve array ; Inititalize all the values in sieve equals to 1 ; Sieve of Eratosthenes ; If current number is prime ; Set all multiples as non - prime ; Function to check if the numbers formed by combining first and last digits generates a prime number or not ; Check if any of the numbers formed is a prime number or not ; Traverse the array of queries ; Extract the last digit ; Extract the first digit ; If any of the two numbers is prime ; Otherwise ; Driver Code ; Computes and stores primes using Sieve ; Function call to perform queries
#include <bits/stdc++.h> NEW_LINE using namespace std ; int sieve [ 105 ] ; void buildSieve ( ) { for ( int i = 2 ; i < 100 ; i ++ ) sieve [ i ] = 1 ; for ( int i = 2 ; i < 100 ; i ++ ) { if ( sieve [ i ] == 1 ) { for ( int j = i * i ; j < 100 ; j += i ) sieve [ j ] = 0 ; } } } bool isAnyPrime ( int first , int last ) { int num1 = first * 10 + last ; int num2 = last * 10 + first ; if ( sieve [ num1 ] == 1 sieve [ num2 ] == 1 ) return true ; else return false ; } void performQueries ( vector < int > q ) { for ( int i = 0 ; i < q . size ( ) ; i ++ ) { int A = q [ i ] ; int last = A % 10 ; int first ; while ( A >= 10 ) A = A / 10 ; first = A ; if ( isAnyPrime ( first , last ) ) cout << " True STRNEWLINE " ; else cout << " False STRNEWLINE " ; } } int main ( ) { vector < int > q = { 30 , 66 } ; buildSieve ( ) ; performQueries ( q ) ; return 0 ; }
Check if a given number N has at least one odd divisor not exceeding N | C ++ program for the above approach ; Function to check whether N has at least one odd divisor not exceeding N - 1 or not ; Stores the value of N ; Reduce the given number N by dividing it by 2 ; If N is divisible by an odd divisor i ; Check if N is an odd divisor after reducing N by dividing it by 2 ; Otherwise ; Driver Code ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; string oddDivisor ( int N ) { int X = N ; while ( N % 2 == 0 ) { N /= 2 ; } for ( int i = 3 ; i * i <= X ; i += 2 ) { if ( N % i == 0 ) { return " Yes " ; } } if ( N != X ) return " Yes " ; return " No " ; } int main ( ) { int N = 10 ; cout << oddDivisor ( N ) ; return 0 ; }
Count numbers from a range whose cube is a Palindrome | C ++ program of the above approach ; Function to check if n is a pallindrome number or not ; Temporarily store n ; Stores reverse of n ; Iterate until temp reduces to 0 ; Extract the last digit ; Add to the start ; Remove the last digit ; If the number and its reverse are equal ; Otherwise ; Function to precompute and store the count of numbers whose cube is a palindrome number ; Iterate upto 10 ^ 4 ; Check if i * i * i is a pallindrome or not ; Convert arr [ ] to prefix sum array ; Driver Code ; Given queries ; Using inclusion - exclusion principle , count required numbers
#include <bits/stdc++.h> NEW_LINE using namespace std ; int arr [ 10005 ] ; int isPalindrome ( int n ) { int temp = n ; int res = 0 ; while ( temp != 0 ) { int rem = temp % 10 ; res = res * 10 + rem ; temp /= 10 ; } if ( res == n ) { return 1 ; } else return 0 ; } void precompute ( ) { for ( int i = 1 ; i <= 10000 ; i ++ ) { if ( isPalindrome ( i * i * i ) ) arr [ i ] = 1 ; else arr [ i ] = 0 ; } for ( int i = 1 ; i <= 10000 ; i ++ ) { arr [ i ] = arr [ i ] + arr [ i - 1 ] ; } } int main ( ) { vector < pair < int , int > > Q = { { 2 , 7 } , { 10 , 25 } } ; precompute ( ) ; for ( auto it : Q ) { cout << arr [ it . second ] - arr [ it . first - 1 ] << " STRNEWLINE " ; } return 0 ; }
Queries to count numbers from a given range which are divisible the sum of their digits | C ++ program of the above approach ; Function to check if the number x is divisible by its sum of digits ; Stores sum of digits of x ; Temporarily store x ; Calculate sum of digits of x ; If x is not divisible by sum ; Otherwise ; Function to perform the precomputation ; Iterate from i equals 1 to 1e5 ; Check if i is divisible by sum of its digits ; Convert arr [ ] to prefix sum array ; Driver code ; Given queries ; Using inclusion - exclusion principle , calculate the result
#include <bits/stdc++.h> NEW_LINE using namespace std ; int arr [ 100005 ] ; bool isDivisible ( int x ) { int sum = 0 ; int temp = x ; while ( x != 0 ) { sum += x % 10 ; x /= 10 ; } if ( temp % sum ) return false ; else return true ; } void precompute ( ) { for ( int i = 1 ; i <= 100000 ; i ++ ) { if ( isDivisible ( i ) ) arr [ i ] = 1 ; else arr [ i ] = 0 ; } for ( int i = 1 ; i <= 100000 ; i ++ ) { arr [ i ] = arr [ i ] + arr [ i - 1 ] ; } } int main ( ) { vector < pair < int , int > > Q = { { 5 , 9 } , { 5 , 20 } } ; precompute ( ) ; for ( auto it : Q ) { cout << arr [ it . second ] - arr [ it . first - 1 ] << " STRNEWLINE " ; } return 0 ; }
Minimize steps required to make two values equal by repeated division by any of their prime factor which is less than M | C ++ program for the above approach ; Stores the prime factor of numbers ; Function to find GCD of a and b ; Base Case ; Otherwise , calculate GCD ; Function to precompute the prime numbers till 1000000 ; Initialize all the positions with their respective values ; Iterate over the range [ 2 , sqrt ( 10 ^ 6 ) ] ; If i is prime number ; Mark it as the factor ; Utility function to count the number of steps to make X and Y equal ; Initialise steps ; Iterate x is at most 1 ; Divide with the smallest prime factor ; If X and Y can 't be made equal ; Return steps ; Function to find the minimum number of steps required to make X and Y equal ; Generate all the prime factors ; Calculate GCD of x and y ; Divide the numbers by their gcd ; If not possible , then return - 1 ; ; Return the resultant number of steps ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int primes [ 1000006 ] ; int gcd ( int a , int b ) { if ( b == 0 ) return a ; else return gcd ( b , a % b ) ; } void preprocess ( ) { for ( int i = 1 ; i <= 1000000 ; i ++ ) primes [ i ] = i ; for ( int i = 2 ; i * i <= 1000000 ; i ++ ) { if ( primes [ i ] == i ) { for ( int j = 2 * i ; j <= 1000000 ; j += i ) { if ( primes [ j ] == j ) primes [ j ] = i ; } } } } int Steps ( int x , int m ) { int steps = 0 ; bool flag = false ; while ( x > 1 ) { if ( primes [ x ] > m ) { flag = true ; break ; } x /= primes [ x ] ; steps ++ ; } if ( flag ) return -1 ; return steps ; } int minimumSteps ( int x , int y , int m ) { preprocess ( ) ; int g = gcd ( x , y ) ; x = x / g ; y = y / g ; int x_steps = Steps ( x , m ) ; int y_steps = Steps ( y , m ) ; if ( x_steps == -1 y_steps == -1 ) return -1 ; return x_steps + y_steps ; } int main ( ) { int X = 160 ; int Y = 180 ; int M = 10 ; cout << ( minimumSteps ( X , Y , M ) ) ; }
Length of longest subsequence consisting of Non | C ++ program for the above approach ; Function to check if n is a deficient number or not ; Stores sum of divisors ; Iterate over the range [ 1 , sqrt ( N ) ] ; If n is divisible by i ; If divisors are equal , add only one of them ; Otherwise add both ; Function to print the longest subsequence which does not contain any deficient numbers ; Stores the count of array elements which are non - deficient ; Traverse the array ; If element is non - deficient ; Return the answer ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool isNonDeficient ( int n ) { int sum = 0 ; for ( int i = 1 ; i <= sqrt ( n ) ; i ++ ) { if ( n % i == 0 ) { if ( n / i == i ) { sum = sum + i ; } else { sum = sum + i ; sum = sum + ( n / i ) ; } } } return sum >= 2 * n ; } int LongestNonDeficientSubsequence ( int arr [ ] , int n ) { int res = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( isNonDeficient ( arr [ i ] ) ) { res += 1 ; } } return res ; } int main ( ) { int arr [ ] = { 13 , 55 , 240 , 32 , 24 , 27 , 56 , 80 , 100 , 330 , 89 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << LongestNonDeficientSubsequence ( arr , N ) ; return 0 ; }
Number of subarrays consisting only of Pronic Numbers | C ++ program for the approach ; Function to check if a number is pronic number or not ; Iterate over the range [ 1 , sqrt ( N ) ] ; Return true if N is pronic ; Otherwise , return false ; Function to count the number of subarrays consisting of pronic numbers ; Stores the count of subarrays ; Stores the number of consecutive array elements which are pronic ; Traverse the array ; If i is pronic ; Return the total count ; Driver code
#include <iostream> NEW_LINE #include <cmath> NEW_LINE using namespace std ; bool isPronic ( int n ) { int range = sqrt ( n ) ; for ( int i = 0 ; i < range + 1 ; i ++ ) { if ( i * ( i + 1 ) == n ) return true ; } return false ; } int countSub ( int * arr , int n ) { int ans = 0 ; int ispro = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( isPronic ( arr [ i ] ) ) ispro += 1 ; else ispro = 0 ; ans += ispro ; } return ans ; } int main ( ) { int arr [ 5 ] = { 5 , 6 , 12 , 3 , 4 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << countSub ( arr , n ) ; return 0 ; }
Replace all array elements with the nearest power of its previous element | CPP program for the above approach ; Function to calculate log x for given base ; Function to replace all array elements with the nearest power of previous adjacent nelement ; For the first element , set the last array element to its previous element ; Traverse the array ; Find K for which x ^ k is nearest to arr [ i ] ; Find the power to x nearest to arr [ i ] ; Update x ; Driver Code ; Function Call ; Display the array
#include <iostream> NEW_LINE #include <cmath> NEW_LINE using namespace std ; int LOG ( int a , int b ) { return log ( a ) / log ( b ) ; } void repbyNP ( int * arr , int n ) { int x = arr [ n - 1 ] ; for ( int i = 0 ; i < n ; i ++ ) { int k = LOG ( arr [ i ] , x ) ; int temp = arr [ i ] ; if ( abs ( pow ( x , k ) - arr [ i ] ) < abs ( pow ( x , k + 1 ) - arr [ i ] ) ) arr [ i ] = pow ( x , k ) ; else arr [ i ] = pow ( x , k + 1 ) ; x = temp ; } } int main ( ) { int arr [ 5 ] = { 2 , 4 , 6 , 3 , 11 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; repbyNP ( arr , n ) ; for ( int i = 0 ; i < n ; i ++ ) cout << arr [ i ] << " ▁ " ; return 0 ; }
Remaining array element after repeated removal of last element and subtraction of each element from next adjacent element | C ++ program for the above approach ; Function to find the last remaining array element after performing the given operations repeatedly ; Stores the resultant sum ; Traverse the array ; Increment sum by arr [ i ] * coefficient of i - th term in ( x - y ) ^ ( N - 1 ) ; Update multiplier ; Return the resultant sum ; Driver Code
#include " bits / stdc + + . h " NEW_LINE using namespace std ; int lastElement ( const int arr [ ] , int n ) { int sum = 0 ; int multiplier = n % 2 == 0 ? -1 : 1 ; for ( int i = 0 ; i < n ; i ++ ) { sum += arr [ i ] * multiplier ; multiplier = multiplier * ( n - 1 - i ) / ( i + 1 ) * ( -1 ) ; } return sum ; } int main ( ) { int arr [ ] = { 3 , 4 , 2 , 1 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << lastElement ( arr , N ) ; return 0 ; }
Maximize count of pairs whose bitwise XOR is even by replacing such pairs with their Bitwise XOR | C ++ program to implement the above approach ; Function to maximize the count of pairs with even XOR possible in an array by given operations ; Stores count of odd array elements ; Traverse the array ; If arr [ i ] is odd ; Stores the total number of even pairs ; Driver Code ; Input ; Function call to count the number of pairs whose XOR is even
#include <bits/stdc++.h> NEW_LINE using namespace std ; int countPairs ( int arr [ ] , int N ) { int odd = 0 ; for ( int i = 0 ; i < N ; i ++ ) { if ( arr [ i ] & 1 ) odd ++ ; } int ans = ( N - odd + odd / 2 - 1 ) + odd / 2 ; return ans ; } int main ( ) { int arr [ ] = { 4 , 6 , 1 , 3 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << countPairs ( arr , N ) ; return 0 ; }
Maximize count of pairs whose Bitwise AND exceeds Bitwise XOR by replacing such pairs with their Bitwise AND | C ++ program for the above approach ; Function to count the number of pairs whose Bitwise AND is greater than the Bitwise XOR ; Stores the frequency of MSB of array elements ; Traverse the array ; Increment count of numbers having MSB at log ( arr [ i ] ) ; Stores total number of pairs ; Traverse the Map ; Return total count of pairs ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int countPairs ( int arr [ ] , int N ) { unordered_map < int , int > freq ; for ( int i = 0 ; i < N ; i ++ ) { freq [ log2 ( arr [ i ] ) ] ++ ; } int pairs = 0 ; for ( auto i : freq ) { pairs += i . second - 1 ; } return pairs ; } int main ( ) { int arr [ ] = { 12 , 9 , 15 , 7 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << countPairs ( arr , N ) ; return 0 ; }
Maximize difference between odd and even indexed array elements by swapping unequal adjacent bits in their binary representations | CPP program for the above approach ; Function to count total number of bits present in a number ; Function to count total set bits in a number ; Stores the count of set bits ; Right shift by 1 ; Return the final count ; Function to find maximum number by shifting two unequal bits ; Count set bits in number n ; Iterate the string bits ; Function to find minimum number by shifting two unequal bits ; Iterate the set bit ; Function to find the maximum difference ; Stores the maximum difference ; Stores the sum of elements placed at odd positions ; Stores the sum of elements placed at even positions ; Traverse the array ; Update CaseOne ; Stores the maximum difference ; Assign value O ; Traverse the array ; Update caseTwo ; Return maximum of caseOne and CaseTwo ; Drivers Code ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; int countBit ( int n ) { return int ( log2 ( n ) ) + 1 ; } int countSetBit ( int n ) { int ans = 0 ; while ( n > 0 ) { ans += ( n & 1 ) ; n >>= 1 ; } return ans ; } int maximize ( int n ) { int bits = countBit ( n ) ; int setBits = countSetBit ( n ) ; int ans = 0 ; for ( int i = 0 ; i < bits ; i ++ ) { if ( i < setBits ) ans |= 1 ; if ( i != setBits - 1 ) ans <<= 1 ; } return ans ; } int minimize ( int n ) { int setBits = countSetBit ( n ) ; int ans = 0 ; for ( int i = 0 ; i < setBits ; i ++ ) { ans |= 1 ; if ( i != setBits - 1 ) ans <<= 1 ; } return ans ; } int maxDiff ( vector < int > arr ) { int caseOne = 0 ; int SumOfOdd = 0 ; int SumOfeven = 0 ; for ( int i = 0 ; i < arr . size ( ) ; i ++ ) { if ( i % 2 ) SumOfOdd += minimize ( arr [ i ] ) ; else SumOfeven += maximize ( arr [ i ] ) ; } caseOne = abs ( SumOfOdd - SumOfeven ) ; int caseTwo = 0 ; SumOfOdd = 0 ; SumOfeven = 0 ; for ( int i = 0 ; i < arr . size ( ) ; i ++ ) { if ( i % 2 ) SumOfOdd += maximize ( arr [ i ] ) ; else SumOfeven += minimize ( arr [ i ] ) ; } caseTwo = abs ( SumOfOdd - SumOfeven ) ; return max ( caseOne , caseTwo ) ; } int main ( ) { vector < int > arr { 54 , 32 , 11 , 23 } ; cout << maxDiff ( arr ) ; }
Sum of numbers obtained by the count of set and non | CPP program for the above approach ; Functino to find the number after processing the diagonal elements ; Store the required number ; Checking for each position ; Store the number of set bits & non - set bits at position i ; Traverse the diagonal elements ; Update count of S if current element is set at position i ; Else update NS ; If number of set bits is > number of non - set bits , add set bits value to the ans ; Return the answer ; Function to find the sum of the numbers generated after processing both the diagonals of the matrix ; Store the primary diagonal elements ; Store the secondary diagonal elements ; Function Call to get the required numbers and return their sum ; Driver Code ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; int processDiagonal ( vector < int > arr ) { int ans = 0 ; int getBit = 1 ; for ( int i = 0 ; i < 32 ; i ++ ) { int S = 0 ; int NS = 0 ; for ( auto j : arr ) { if ( getBit & j ) S += 1 ; else NS += 1 ; } if ( S > NS ) ans += pow ( 2 , i ) ; getBit <<= 1 ; } return ans ; } int findSum ( vector < vector < int > > mat ) { int i = 0 ; int j = 0 ; vector < int > priDiag ; while ( i < mat . size ( ) ) { priDiag . push_back ( mat [ i ] [ j ] ) ; i += 1 ; j += 1 ; } i = 0 ; j = mat . size ( ) - 1 ; vector < int > secDiag ; while ( i < mat . size ( ) ) { secDiag . push_back ( mat [ i ] [ j ] ) ; i += 1 ; j -= 1 ; } return processDiagonal ( priDiag ) + processDiagonal ( secDiag ) ; } int main ( ) { vector < vector < int > > mat { { 1 , 2 , 3 } , { 4 , 5 , 6 } , { 7 , 8 , 9 } } ; cout << findSum ( mat ) << endl ; }
Minimize difference between two sequences obtained by splitting first N powers of 2 | C ++ program for the above approach ; Function to partition first N powers of 2 into two subsequences with minimum difference between their sum ; Largest element in the first part ; Place N / 2 - 1 smallest elements in the first sequence ; Place remaining N / 2 elements in the second sequence ; Print the minimum difference ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void minimumDifference ( int N ) { int sum1 = ( 1 << N ) , sum2 = 0 ; for ( int i = 1 ; i < N / 2 ; i ++ ) sum1 += ( 1 << i ) ; for ( int i = N / 2 ; i < N ; i ++ ) sum2 += ( 1 << i ) ; cout << sum1 - sum2 ; } int main ( ) { int N = 4 ; minimumDifference ( N ) ; return 0 ; }
Modulo Operator ( % ) in C / C ++ with Examples | Program to illustrate the working of the modulo operator ; To store two integer values ; To store the result of the modulo expression
#include <iostream> NEW_LINE using namespace std ; int main ( void ) { int x , y ; int result ; x = -3 ; y = 4 ; result = x % y ; cout << result << endl ; x = 4 ; y = -2 ; result = x % y ; cout << result << endl ; x = -3 ; y = -4 ; result = x % y ; cout << result ; return 0 ; }
Check whether N can be a Perfect Cube after adding or subtracting K | C ++ implementation of the above approach ; Function to check if a number is a perfect Cube or not ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool isPerfectCube ( int x ) { int cr = round ( cbrt ( x ) ) ; return ( cr * cr * cr == x ) ; } void canBePerfectCube ( int N , int K ) { if ( isPerfectCube ( N + K ) || isPerfectCube ( N - K ) ) cout << " Yes STRNEWLINE " ; else cout << " No STRNEWLINE " ; } int main ( ) { int N = 7 , K = 1 ; canBePerfectCube ( N , K ) ; N = 5 , K = 4 ; canBePerfectCube ( N , K ) ; N = 7 , K = 2 ; canBePerfectCube ( N , K ) ; return 0 ; }
Floor square root without using sqrt ( ) function : Recursive | C ++ implementation to find the square root of the number N without using sqrt ( ) function ; Function to find the square root of the number N using BS ; If the range is still valid ; Find the mid - value of the range ; Base Case ; Condition to check if the left search space is useless ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int sqrtSearch ( int low , int high , int N ) { if ( low <= high ) { int mid = ( low + high ) / 2 ; if ( ( mid * mid <= N ) && ( ( mid + 1 ) * ( mid + 1 ) > N ) ) { return mid ; } else if ( mid * mid < N ) { return sqrtSearch ( mid + 1 , high , N ) ; } else { return sqrtSearch ( low , mid - 1 , N ) ; } } return low ; } int main ( ) { int N = 25 ; cout << sqrtSearch ( 0 , N , N ) << endl ; return 0 ; }
Common divisors of N numbers | C ++ program to find all common divisors of N numbers ; Function to calculate gcd of two numbers ; Function to print all the common divisors ; Variable to find the gcd of N numbers ; Set to store all the common divisors ; Finding GCD of the given N numbers ; Finding divisors of the HCF of n numbers ; Print all the divisors ; Driver 's Code ; Function to print all the common divisors
#include <bits/stdc++.h> NEW_LINE using namespace std ; int gcd ( int a , int b ) { if ( a == 0 ) return b ; return gcd ( b % a , a ) ; } void printAllDivisors ( int arr [ ] , int N ) { int g = arr [ 0 ] ; set < int > divisors ; for ( int i = 1 ; i < N ; i ++ ) { g = gcd ( arr [ i ] , g ) ; } for ( int i = 1 ; i * i <= g ; i ++ ) { if ( g % i == 0 ) { divisors . insert ( i ) ; if ( g / i != i ) divisors . insert ( g / i ) ; } } for ( auto & it : divisors ) cout << it << " ▁ " ; } int main ( ) { int arr [ ] = { 6 , 90 , 12 , 18 , 30 , 24 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; printAllDivisors ( arr , n ) ; return 0 ; }
Recursive Program to print multiplication table of a number | C ++ program to print table of a number using recursion ; Function that print the table of a given number using recursion ; Base Case ; Print the table for current iteration ; Recursive call to next iteration ; Driver Code ; Input number whose table is to print ; Function call to print the table
#include <iostream> NEW_LINE using namespace std ; void mul_table ( int N , int i ) { if ( i > 10 ) return ; cout << N << " ▁ * ▁ " << i << " ▁ = ▁ " << N * i << endl ; return mul_table ( N , i + 1 ) ; } int main ( ) { int N = 8 ; mul_table ( N , 1 ) ; return 0 ; }
Find the largest composite number that divides N but is strictly lesser than N | C ++ program to find the largest composite number that divides N which is less than N ; Function to check whether a number is prime or not ; Corner case ; Check from 2 to n - 1 ; Function that find the largest composite number which divides N and less than N ; Find the prime number ; Driver 's Code ; Get the smallest prime factor ; Check if ( N / a ) is prime or not If Yes print " - 1" ; Else print largest composite number ( N / a )
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool isPrime ( int n ) { if ( n <= 1 ) return false ; for ( int i = 2 ; i < n ; i ++ ) if ( n % i == 0 ) return false ; return true ; } int getSmallestPrimefactor ( int n ) { for ( int i = 2 ; i <= sqrt ( n ) ; i ++ ) { if ( n % i == 0 ) return i ; } } int main ( ) { int N = 100 ; int a ; a = getSmallestPrimefactor ( N ) ; if ( isPrime ( N / a ) ) { cout << " - 1" ; } else { cout << N / a ; } return 0 ; }
Check if N and M can be made equal by increasing N by A and decreasing M by B | C ++ program to check if two numbers can be made equal by increasing the first by a and decreasing the second by b ; Function to whether the numbers can be made equal or not ; Check whether the numbers can reach an equal point or not ; M and N cannot be made equal by increasing M and decreasing N when M is already greater than N ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool checkEqualNo ( int m , int n , int a , int b ) { if ( m <= n ) { if ( ( n - m ) % ( a + b ) == 0 ) { return true ; } else { return false ; } } else { return false ; } } int main ( ) { int M = 2 , N = 8 ; int A = 3 , B = 3 ; if ( checkEqualNo ( M , N , A , B ) ) cout << " Yes " << endl ; else cout << " No " << endl ; return 0 ; }
XOR and OR of all N | C ++ program to find the XOR and OR of all palindrome numbers of N digits ; Function to check if a number is palindrome or not ; Convert the num n to string ; Iterate over string to check whether it is palindromic or not ; Function to find XOR of all N - digits palindrome number ; To store the XOR and OR of all palindromic number ; Starting N - digit palindromic number ; Ending N - digit palindromic number ; Iterate over starting and / ending number ; To check if i is palindromic or not ; Print the XOR and OR of all palindromic number ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool ispalin ( int num ) { string s = to_string ( num ) ; int st = 0 , ed = s . size ( ) - 1 ; while ( st <= ed ) { if ( s [ st ] != s [ ed ] ) return false ; st ++ ; ed -- ; } return true ; } void CalculateXORandOR ( int n ) { int CalculateXOR = 0 ; int CalculateOR = 0 ; int start = pow ( 10 , n - 1 ) ; int end = pow ( 10 , n ) - 1 ; for ( int i = start ; i <= end ; i ++ ) { if ( ispalin ( i ) ) { CalculateXOR = CalculateXOR ^ i ; CalculateOR = CalculateOR | i ; } } cout << " XOR ▁ = ▁ " << CalculateXOR ; cout << " ▁ OR ▁ = ▁ " << CalculateOR ; } int main ( ) { int n = 4 ; CalculateXORandOR ( n ) ; return 0 ; }
Sum of all palindromic numbers lying in the range [ L , R ] for Q queries | C ++ program to find the sum of all palindrome numbers in the given range ; pref [ ] array to precompute the sum of all palindromic number ; Function that return number num if num is palindromic else return 0 ; Convert num to string ; Function to precompute the sum of all palindrome numbers upto 100000 ; checkPalindrome ( ) return the number i if i is palindromic else return 0 ; Function to print the sum for each query ; Function to print sum of all palindromic numbers between [ L , R ] ; Function that pre computes the sum of all palindromic numbers ; Iterate over all Queries to print the sum ; Driver code ; Queries ; Function that print the the sum of all palindromic number in Range [ L , R ]
#include <bits/stdc++.h> NEW_LINE using namespace std ; long long pref [ 100001 ] ; int checkPalindrome ( int num ) { string str = to_string ( num ) ; int l = 0 , r = str . length ( ) - 1 ; while ( l < r ) { if ( str [ l ] != str [ r ] ) { return 0 ; } l ++ ; r -- ; } return num ; } void preCompute ( ) { for ( int i = 1 ; i <= 100000 ; ++ i ) { pref [ i ] = pref [ i - 1 ] + checkPalindrome ( i ) ; } } void printSum ( int L , int R ) { cout << pref [ R ] - pref [ L - 1 ] << endl ; } void printSumPalindromic ( int arr [ ] [ 2 ] , int Q ) { preCompute ( ) ; for ( int i = 0 ; i < Q ; i ++ ) { printSum ( arr [ i ] [ 0 ] , arr [ i ] [ 1 ] ) ; } } int main ( ) { int Q = 2 ; int arr [ ] [ 2 ] = { { 10 , 13 } , { 12 , 21 } } ; printSumPalindromic ( arr , Q ) ; return 0 ; }
Sum of alternating sign Squares of first N natural numbers | C ++ program to find Sum of alternating sign Squares of first N natural numbers ; Function to calculate the alternating sign sum ; Variable to store the sum ; Loop to iterate each number from 1 to N ; The alternating sign is put by checking if the number is even or odd ; Add the square with the sign ; Add the square with the sign ; Driver code
#include <iostream> NEW_LINE using namespace std ; int summation ( int n ) { int sum = 0 ; for ( int i = 1 ; i <= n ; i ++ ) { if ( i % 2 == 1 ) sum += ( i * i ) ; else sum -= ( i * i ) ; } return sum ; } int main ( ) { int N = 2 ; cout << summation ( N ) ; return 0 ; }
Sum of alternating sign Squares of first N natural numbers | C ++ program to find Sum of alternating sign Squares of first N natural numbers ; Function to calculate the alternating sign sum ; Variable to store the absolute sum ; Variable to store the sign ; Variable to store the resultant sum ; Driver code
#include <iostream> NEW_LINE using namespace std ; int summation ( int n ) { int abs_sum = n * ( n + 1 ) / 2 ; int sign = n + 1 % 2 == 0 ? 1 : -1 ; int result_sum = sign * abs_sum ; return result_sum ; } int main ( ) { int N = 2 ; cout << summation ( N ) ; return 0 ; }
Count pairs from 1 to N such that their Sum is divisible by their XOR | C ++ program to count pairs from 1 to N such that their Sum is divisible by their XOR ; Function to count pairs ; variable to store count ; Generate all possible pairs such that 1 <= x < y < n ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int countPairs ( int n ) { int count = 0 ; for ( int x = 1 ; x < n ; x ++ ) { for ( int y = x + 1 ; y <= n ; y ++ ) { if ( ( y + x ) % ( y ^ x ) == 0 ) count ++ ; } } return count ; } int main ( ) { int n = 6 ; cout << countPairs ( n ) ; return 0 ; }
Count pairs in array such that one element is power of another | C ++ program to count pairs in array such that one element is power of another ; Function to check if given number number y is power of x ; log function to calculate value ; compare to the result1 or result2 both are equal ; Function to find pairs from array ; Iterate through all pairs ; Increment count if one is the power of other ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool isPower ( int x , int y ) { int res1 = log ( y ) / log ( x ) ; double res2 = log ( y ) / log ( x ) ; return ( res1 == res2 ) ; } int countPower ( int arr [ ] , int n ) { int res = 0 ; for ( int i = 0 ; i < n ; i ++ ) for ( int j = i + 1 ; j < n ; j ++ ) if ( isPower ( arr [ i ] , arr [ j ] ) || isPower ( arr [ j ] , arr [ i ] ) ) res ++ ; return res ; } int main ( ) { int a [ ] = { 16 , 2 , 3 , 9 } ; int n = sizeof ( a ) / sizeof ( a [ 0 ] ) ; cout << countPower ( a , n ) ; return 0 ; }
Find the original Array using XOR values of all adjacent elements | C ++ implementation to find the Array from the XOR array of the adjacent elements of array ; XOR of all elements from 1 to N ; Function to find the Array from the XOR Array ; Take a vector to store the permutation ; XOR of N natural numbers ; Loop to find the XOR of adjacent elements of the XOR Array ; Loop to find the other elements of the permutation ; Finding the next and next elements ; Driver Code ; Required Permutation
#include <bits/stdc++.h> NEW_LINE using namespace std ; int xor_all_elements ( int n ) { switch ( n & 3 ) { case 0 : return n ; case 1 : return 1 ; case 2 : return n + 1 ; case 3 : return 0 ; } } vector < int > findArray ( int xorr [ ] , int n ) { vector < int > arr ; int xor_all = xor_all_elements ( n ) ; int xor_adjacent = 0 ; for ( int i = 0 ; i < n - 1 ; i += 2 ) { xor_adjacent = xor_adjacent ^ xorr [ i ] ; } int last_element = xor_all ^ xor_adjacent ; arr . push_back ( last_element ) ; for ( int i = n - 2 ; i >= 0 ; i -- ) { last_element = xorr [ i ] ^ last_element ; arr . push_back ( last_element ) ; } return arr ; } int main ( ) { vector < int > arr ; int xorr [ ] = { 7 , 5 , 3 , 7 } ; int n = 5 ; arr = findArray ( xorr , n ) ; for ( int i = n - 1 ; i >= 0 ; i -- ) { cout << arr [ i ] << " ▁ " ; } }
Sum of non | C ++ implementation of the above approach ; Function to return a vector which consists the sum of four portions of the matrix ; Iterating through the matrix ; Condition for selecting all values before the second diagonal of metrics ; Top portion of the matrix ; Left portion of the matrix ; Bottom portion of the matrix ; Right portion of the matrix ; Adding all the four portions into a vector ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int sumOfParts ( int * arr , int N ) { int sum_part1 = 0 , sum_part2 = 0 , sum_part3 = 0 , sum_part4 = 0 ; int totalsum = 0 ; for ( int i = 0 ; i < N ; i ++ ) { for ( int j = 0 ; j < N ; j ++ ) { if ( i + j < N - 1 ) { if ( i < j and i != j and i + j ) sum_part1 += ( arr + i * N ) [ j ] ; else if ( i != j ) sum_part2 += ( arr + i * N ) [ j ] ; } else { if ( i > j and i + j != N - 1 ) sum_part3 += ( arr + i * N ) [ j ] ; else { if ( i + j != N - 1 and i != j ) sum_part4 += ( arr + i * N ) [ j ] ; } } } } totalsum = sum_part1 + sum_part2 + sum_part3 + sum_part4 ; return totalsum ; } int main ( ) { int N = 4 ; int arr [ N ] [ N ] = { { 1 , 2 , 3 , 4 } , { 5 , 6 , 7 , 8 } , { 9 , 10 , 11 , 12 } , { 13 , 14 , 15 , 16 } } ; cout << sumOfParts ( ( int * ) arr , N ) ; }
Check if X and Y can be made zero by using given operation any number of times | C ++ implementation of the approach ; Function to check if X and Y can be made equal to zero by using given operation any number of times ; Check for the two conditions ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void ifPossible ( int X , int Y ) { if ( X > Y ) swap ( X , Y ) ; if ( ( X + Y ) % 5 == 0 and 3 * X >= 2 * Y ) cout << " Yes " ; else cout << " No " ; } int main ( ) { int X = 33 , Y = 27 ; ifPossible ( X , Y ) ; return 0 ; }
Largest Even and Odd N | C ++ implementation of the approach ; Function to print the largest n - digit even and odd numbers in hexadecimal number system ; Append ' F ' ( N - 1 ) times ; Append ' E ' for an even number ; Append ' F ' for an odd number ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void findNumbers ( int n ) { string ans = string ( n - 1 , ' F ' ) ; string even = ans + ' E ' ; string odd = ans + ' F ' ; cout << " Even : ▁ " << even << endl ; cout << " Odd : ▁ " << odd << endl ; } int main ( ) { int n = 2 ; findNumbers ( n ) ; return 0 ; }
Program to compute log a to any base b ( logb a ) | C ++ program to find log ( a ) on any base b ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int log_a_to_base_b ( int a , int b ) { return log ( a ) / log ( b ) ; } int main ( ) { int a = 3 ; int b = 2 ; cout << log_a_to_base_b ( a , b ) << endl ; a = 256 ; b = 4 ; cout << log_a_to_base_b ( a , b ) << endl ; return 0 ; }
Program to compute log a to any base b ( logb a ) | C ++ program to find log ( a ) on any base b using Recursion ; Recursive function to compute log a to the base b ; Driver code
#include <iostream> NEW_LINE using namespace std ; int log_a_to_base_b ( int a , int b ) { return ( a > b - 1 ) ? 1 + log_a_to_base_b ( a / b , b ) : 0 ; } int main ( ) { int a = 3 ; int b = 2 ; cout << log_a_to_base_b ( a , b ) << endl ; a = 256 ; b = 4 ; cout << log_a_to_base_b ( a , b ) << endl ; return 0 ; }
Largest and Smallest N | C ++ program to find the largest and smallest N - digit numbers in Hexa - Decimal Number System ; Function to return the largest N - digit number in Hexa - Decimal Number System ; Append ' F ' N times ; Function to return the smallest N - digit number in Hexa - Decimal Number System ; Append '0' ( N - 1 ) times to 1 ; Function to print the largest and smallest N - digit Hexa - Decimal number ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; string findLargest ( int N ) { string largest = string ( N , ' F ' ) ; return largest ; } string findSmallest ( int N ) { string smallest = "1" + string ( ( N - 1 ) , '0' ) ; return smallest ; } void print ( int largest ) { cout << " Largest : ▁ " << findLargest ( largest ) << endl ; cout << " Smallest : ▁ " << findSmallest ( largest ) << endl ; } int main ( ) { int N = 4 ; print ( N ) ; return 0 ; }
Highest and Smallest power of K less than and greater than equal to N respectively | C ++ implementation of the approach ; Function to return the highest power of k less than or equal to n ; Function to return the smallest power of k greater than or equal to n ; Function to print the result ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int prevPowerofK ( int n , int k ) { int p = ( int ) ( log ( n ) / log ( k ) ) ; return ( int ) pow ( k , p ) ; } int nextPowerOfK ( int n , int k ) { return prevPowerofK ( n , k ) * k ; } void printResult ( int n , int k ) { cout << prevPowerofK ( n , k ) << " ▁ " << nextPowerOfK ( n , k ) << endl ; } int main ( ) { int n = 25 , k = 3 ; printResult ( n , k ) ; return 0 ; }
Check if all elements of the given array can be made 0 by decrementing value in pairs | C ++ program to make the array zero by decrementing value in pairs ; Function to check if all the elements can be made 0 in an array ; Variable to store sum and maximum element in an array ; Loop to calculate the sum and max value of the given array ; If n is 1 or sum is odd or sum - max element < max then no solution ; For the remaining case , print Yes ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void canMake ( int n , int ar [ ] ) { int sum = 0 , maxx = -1 ; for ( int i = 0 ; i < n ; i ++ ) { sum += ar [ i ] ; maxx = max ( maxx , ar [ i ] ) ; } if ( n == 1 sum % 2 == 1 sum - maxx < maxx ) { cout << " No STRNEWLINE " ; } else { cout << " Yes STRNEWLINE " ; } } int main ( ) { int n = 6 ; int arr [ ] = { 1 , 1 , 2 , 3 , 6 , 11 } ; canMake ( n , arr ) ; return 0 ; }
Sum of all Perfect Squares lying in the range [ L , R ] for Q queries | C ++ program to find the sum of all perfect squares in the given range ; Array to precompute the sum of squares from 1 to 100010 so that for every query , the answer can be returned in O ( 1 ) . ; Function to check if a number is a perfect square or not ; Find floating point value of square root of x . ; If square root is an integer ; Function to precompute the perfect squares upto 100000. ; Function to print the sum for each query ; Driver code ; To calculate the precompute function ; Calling the printSum function for every query
#include <bits/stdc++.h> NEW_LINE #define ll int NEW_LINE using namespace std ; long long pref [ 100010 ] ; int isPerfectSquare ( long long int x ) { long double sr = sqrt ( x ) ; return ( ( sr - floor ( sr ) ) == 0 ) ? x : 0 ; } void compute ( ) { for ( int i = 1 ; i <= 100000 ; ++ i ) { pref [ i ] = pref [ i - 1 ] + isPerfectSquare ( i ) ; } } void printSum ( int L , int R ) { int sum = pref [ R ] - pref [ L - 1 ] ; cout << sum << " ▁ " ; } int main ( ) { compute ( ) ; int Q = 4 ; int arr [ ] [ 2 ] = { { 1 , 10 } , { 1 , 100 } , { 2 , 25 } , { 4 , 50 } } ; for ( int i = 0 ; i < Q ; i ++ ) { printSum ( arr [ i ] [ 0 ] , arr [ i ] [ 1 ] ) ; } return 0 ; }
Program to find all Factors of a Number using recursion | C ++ program to find all the factors of a number using recursion ; Recursive function to print factors of a number ; Checking if the number is less than N ; Calling the function recursively for the next number ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void factors ( int n , int i ) { if ( i <= n ) { if ( n % i == 0 ) { cout << i << " ▁ " ; } factors ( n , i + 1 ) ; } } int main ( ) { int N = 16 ; factors ( N , 1 ) ; }
Maximize value of ( a + b ) such that ( a * a | C ++ program to maximize the value of ( a + b ) such that ( a * a - b * b = N ) ; Function to maximize the value of ( a + b ) such that ( a * a - b * b = n ) ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int maxValue ( int n ) { return n ; } int main ( ) { int n = 1 ; cout << maxValue ( n ) ; return 0 ; }
Maximum number of edges that N | C ++ implementation to find the maximum number of edges for triangle free graph ; Function to find the maximum number of edges in a N - vertex graph . ; According to the Mantel 's theorem the maximum number of edges will be floor of [(n^2)/4] ; Driver Function
#include <bits/stdc++.h> NEW_LINE using namespace std ; int solve ( int n ) { int ans = ( n * n / 4 ) ; return ans ; } int main ( ) { int n = 10 ; cout << solve ( n ) << endl ; return 0 ; }
Multiplication table till N rows where every Kth row is table of K upto Kth term | C ++ program to print multiplication table till N rows where every Kth row is the table of K up to Kth term ; Function to print the multiplication table upto K - th term ; For loop to iterate from 1 to N where i serves as the value of K ; Inner loop which at every iteration goes till i ; Printing the table value for i ; New line after every row ; Driver code
#include <iostream> NEW_LINE using namespace std ; void printMultiples ( int N ) { for ( int i = 1 ; i <= N ; i ++ ) { for ( int j = 1 ; j <= i ; j ++ ) { cout << ( i * j ) << " ▁ " ; } cout << endl ; } } int main ( ) { int N = 5 ; printMultiples ( N ) ; return 0 ; }
Boundary Value Analysis : Nature of Roots of a Quadratic equation | C ++ program to check the nature of the roots ; BVA for nature of roots of a quadratic equation ; If a = 0 , D / 2 a will yield exception Hence it is not a valid Quadratic Equation ; If D > 0 , it will be Real Roots ; If D == 0 , it will be Equal Roots ; If D < 0 , it will be Imaginary Roots ; Function to check for all testcases ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void nature_of_roots ( int a , int b , int c ) { if ( a == 0 ) { cout << " Not ▁ a ▁ Quadratic ▁ Equation " << endl ; return ; } int D = b * b - 4 * a * c ; if ( D > 0 ) { cout << " Real ▁ Roots " << endl ; } else if ( D == 0 ) { cout << " Equal ▁ Roots " << endl ; } else { cout << " Imaginary ▁ Roots " << endl ; } } void checkForAllTestCase ( ) { cout << " Testcase " << " TABSYMBOL a TABSYMBOL b TABSYMBOL c TABSYMBOL Actual ▁ Output " << endl ; cout << endl ; int a , b , c ; int testcase = 1 ; while ( testcase <= 13 ) { if ( testcase == 1 ) { a = 0 ; b = 50 ; c = 50 ; } else if ( testcase == 2 ) { a = 1 ; b = 50 ; c = 50 ; } else if ( testcase == 3 ) { a = 50 ; b = 50 ; c = 50 ; } else if ( testcase == 4 ) { a = 99 ; b = 50 ; c = 50 ; } else if ( testcase == 5 ) { a = 100 ; b = 50 ; c = 50 ; } else if ( testcase == 6 ) { a = 50 ; b = 0 ; c = 50 ; } else if ( testcase == 7 ) { a = 50 ; b = 1 ; c = 50 ; } else if ( testcase == 8 ) { a = 50 ; b = 99 ; c = 50 ; } else if ( testcase == 9 ) { a = 50 ; b = 100 ; c = 50 ; } else if ( testcase == 10 ) { a = 50 ; b = 50 ; c = 0 ; } else if ( testcase == 11 ) { a = 50 ; b = 50 ; c = 1 ; } else if ( testcase == 12 ) { a = 50 ; b = 50 ; c = 99 ; } else if ( testcase == 13 ) { a = 50 ; b = 50 ; c = 100 ; } cout << " TABSYMBOL " << testcase << " TABSYMBOL " << a << " TABSYMBOL " << b << " TABSYMBOL " << c << " TABSYMBOL " ; nature_of_roots ( a , b , c ) ; cout << endl ; testcase ++ ; } } int main ( ) { checkForAllTestCase ( ) ; return 0 ; }
Find if the Vacation can be taken or not | C ++ program to find if the Vacation can be taken or not ; Function to find if the Vacation is possible or not ; Find the required number of hours of study ; find the hours of study that can be done if the vacation is taken ; check if the required hours are less than or equal to the hours of study that can be done if the vacation is taken ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int isPossible ( int N , int S , int C , int H , int L , int T ) { int total_time_required = S * C * H ; int available_time_after_vacation = ( N - L ) * T ; if ( available_time_after_vacation >= total_time_required ) return 1 ; return 0 ; } int main ( ) { int N = 12 , S = 5 , C = 8 , H = 3 , L = 2 , T = 20 ; if ( isPossible ( N , S , C , H , L , T ) ) cout << " Yes " << endl ; else cout << " No " << endl ; N = 1 , S = 2 , C = 3 , H = 4 , L = 5 , T = 6 ; if ( isPossible ( N , S , C , H , L , T ) ) cout << " Yes " << endl ; else cout << " No " << endl ; return 0 ; }
Find Maximum and Minimum of two numbers using Absolute function | C ++ program to find maximum and minimum using Absolute function ; Function to return maximum among the two numbers ; Function to return minimum among the two numbers ; Driver code ; Displaying the maximum value ; Displaying the minimum value
#include <bits/stdc++.h> NEW_LINE using namespace std ; int maximum ( int x , int y ) { return ( ( x + y + abs ( x - y ) ) / 2 ) ; } int minimum ( int x , int y ) { return ( ( x + y - abs ( x - y ) ) / 2 ) ; } int main ( ) { int x = 99 , y = 18 ; cout << " Maximum : ▁ " << maximum ( x , y ) << endl ; cout << " Minimum : ▁ " << minimum ( x , y ) << endl ; return 0 ; }
Find an array of size N having exactly K subarrays with sum S | C ++ program to find array with K subarrays with sum S ; Function to find array with K subarrays with sum S ; Driver Code ; Function call
#include <bits/stdc++.h> NEW_LINE using namespace std ; void SubarraysWithSumS ( int n , int k , int s ) { for ( int i = 0 ; i < k ; i ++ ) cout << s << " ▁ " ; for ( int i = k ; i < n ; i ++ ) cout << s + 1 << " ▁ " ; } int main ( ) { int n = 4 , k = 2 , s = 3 ; SubarraysWithSumS ( n , k , s ) ; return 0 ; }
Minimum number of cuts required to pay salary from N length Gold Bar | CPP Implementation to find the minimum number of cuts to pay the worker . ; Function to find the minimum number of cuts to pay the worker . ; Nearest Integer to the Log value of the number N ; Driver code ; Cuts Required in the Length of 15
#include <bits/stdc++.h> NEW_LINE using namespace std ; int pay ( int n ) { int cuts = int ( log ( n ) / log ( 2 ) ) ; return cuts ; } int main ( ) { int n = 5 ; int cuts = pay ( n ) ; cout << cuts << endl ; n = 15 ; cuts = pay ( n ) ; cout << ( cuts ) ; return 0 ; }
Sum of Maximum and Minimum prime factor of every number in the Array | C ++ implementation of the approach ; max_prime [ i ] represent maximum prime number that divides the number i ; min_prime [ i ] represent minimum prime number that divides the number i ; Function to store the minimum prime factor and the maximum prime factor in two arrays ; Check for prime number if min_prime [ i ] > 0 , then it is not a prime number ; if i is a prime number min_prime number that divide prime number and max_prime number that divide prime number is the number itself . ; If this number is being visited for first time then this divisor must be the smallest prime number that divides this number ; The last prime number that divides this number will be maximum . ; Function to find the sum of the minimum and the maximum prime factors of every number from the given array ; Pre - calculation ; For every element of the given array ; The sum of its smallest and largest prime factor ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; const int MAX = 100000 ; int max_prime [ MAX ] ; int min_prime [ MAX ] ; void sieve ( int n ) { for ( int i = 2 ; i <= n ; ++ i ) { if ( min_prime [ i ] > 0 ) { continue ; } min_prime [ i ] = i ; max_prime [ i ] = i ; int j = i + i ; while ( j <= n ) { if ( min_prime [ j ] == 0 ) { min_prime [ j ] = i ; } max_prime [ j ] = i ; j += i ; } } } void findSum ( int arr [ ] , int n ) { sieve ( MAX ) ; for ( int i = 0 ; i < n ; i ++ ) { int sum = min_prime [ arr [ i ] ] + max_prime [ arr [ i ] ] ; cout << sum << " ▁ " ; } } int main ( ) { int arr [ ] = { 5 , 10 , 15 , 20 , 25 , 30 } ; int n = sizeof ( arr ) / sizeof ( int ) ; findSum ( arr , n ) ; return 0 ; }
Pair of integers ( a , b ) which satisfy the given equations | C ++ program to count the pair of integers ( a , b ) which satisfy the equation a ^ 2 + b = n and a + b ^ 2 = m ; Function to count valid pairs ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int pairCount ( int n , int m ) { int cnt = 0 , b , a ; for ( b = 0 ; b <= sqrt ( m ) ; b ++ ) { a = m - b * b ; if ( a * a + b == n ) { cnt ++ ; } } return cnt ; } int main ( ) { int n = 9 , m = 3 ; cout << pairCount ( n , m ) << endl ; return 0 ; }
Largest Divisor for each element in an array other than 1 and the number itself | C ++ implementation of the approach ; Divisors array to keep track of the maximum divisor ; Function to pre - compute the prime numbers and largest divisors ; Visited array to keep track of prime numbers ; 0 and 1 are not prime numbers ; Initialising divisors [ i ] = i ; For all the numbers divisible by 2 the maximum divisor will be number / 2 ; If divisors [ i ] is not equal to i then this means that divisors [ i ] contains minimum prime divisor for the number ; Update the answer to i / smallest_prime_divisor [ i ] ; Condition if i is a prime number ; If divisors [ j ] is equal to j then this means that i is the first prime divisor for j so we update divi [ j ] = i ; If the current element is prime then it has no divisors other than 1 and itself ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; #define int long long NEW_LINE const int maxin = 100001 ; int divisors [ maxin ] ; void Calc_Max_Div ( int arr [ ] , int n ) { bool vis [ maxin ] ; memset ( vis , 1 , maxin ) ; vis [ 0 ] = vis [ 1 ] = 0 ; for ( int i = 1 ; i <= maxin ; i ++ ) divisors [ i ] = i ; for ( int i = 4 ; i <= maxin ; i += 2 ) { vis [ i ] = 0 ; divisors [ i ] = i / 2 ; } for ( int i = 3 ; i <= maxin ; i += 2 ) { if ( divisors [ i ] != i ) { divisors [ i ] = i / divisors [ i ] ; } if ( vis [ i ] == 1 ) { for ( int j = i * i ; j < maxin ; j += i ) { vis [ j ] = 0 ; if ( divisors [ j ] == j ) divisors [ j ] = i ; } } } for ( int i = 0 ; i < n ; i ++ ) { if ( divisors [ arr [ i ] ] == arr [ i ] ) cout << " - 1 ▁ " ; else cout << divisors [ arr [ i ] ] << " ▁ " ; } } int32_t main ( ) { int arr [ ] = { 5 , 6 , 7 , 8 , 9 , 10 } ; int n = sizeof ( arr ) / sizeof ( int ) ; Calc_Max_Div ( arr , n ) ; return 0 ; }
Given a number N in decimal base , find the sum of digits in any base B | C ++ Implementation to Compute Sum of Digits of Number N in Base B ; Function to compute sum of Digits of Number N in base B ; Initialize sum with 0 ; Compute unit digit of the number ; Add unit digit in sum ; Update value of Number ; Driver function
#include <iostream> NEW_LINE using namespace std ; int sumOfDigit ( int n , int b ) { int unitDigit , sum = 0 ; while ( n > 0 ) { unitDigit = n % b ; sum += unitDigit ; n = n / b ; } return sum ; } int main ( ) { int n = 50 ; int b = 2 ; cout << sumOfDigit ( n , b ) ; return 0 ; }
Find the Nth digit from right in base B of the given number in Decimal base | C ++ Implementation to find Nth digit from right in base B ; Function to compute Nth digit from right in base B ; Skip N - 1 Digits in Base B ; Nth Digit from right in Base B ; Driver Code
#include <iostream> NEW_LINE using namespace std ; int nthDigit ( int a , int n , int b ) { for ( int i = 1 ; i < n ; i ++ ) a = a / b ; return a % b ; } int main ( ) { int a = 100 ; int n = 3 ; int b = 4 ; cout << nthDigit ( a , n , b ) ; return 0 ; }
Find three prime numbers with given sum | C ++ implementation of the approach ; The vector primes holds the prime numbers ; Function to generate prime numbers ; Initialize the array elements to 0 s ; Set the non - primes to true ; Fill the vector primes with prime numbers which are marked as false in the numbers array ; Function to print three prime numbers which sum up to the number N ; Take the first prime number ; Take the second prime number ; Subtract the two prime numbers from the N to obtain the third number ; If the third number is prime ; Print the three prime numbers if the solution exists ; Driver code ; Function for generating prime numbers using Sieve of Eratosthenes ; Function to print the three prime numbers whose sum is equal to N
#include <bits/stdc++.h> NEW_LINE using namespace std ; const int MAX = 100001 ; vector < int > primes ; void initialize ( ) { bool numbers [ MAX ] = { } ; int n = MAX ; for ( int i = 2 ; i * i <= n ; i ++ ) if ( ! numbers [ i ] ) for ( int j = i * i ; j <= n ; j += i ) numbers [ j ] = true ; for ( int i = 2 ; i <= n ; i ++ ) if ( numbers [ i ] == false ) primes . push_back ( i ) ; } void findNums ( int num ) { bool ans = false ; int first = -1 , second = -1 , third = -1 ; for ( int i = 0 ; i < num ; i ++ ) { first = primes [ i ] ; for ( int j = 0 ; j < num ; j ++ ) { second = primes [ j ] ; third = num - first - second ; if ( binary_search ( primes . begin ( ) , primes . end ( ) , third ) ) { ans = true ; break ; } } if ( ans ) break ; } if ( ans ) cout << first << " ▁ " << second << " ▁ " << third << endl ; else cout << -1 << endl ; } int main ( ) { int n = 101 ; initialize ( ) ; findNums ( n ) ; return 0 ; }
Print all maximal increasing contiguous sub | C ++ Implementation to print all the Maximal Increasing Sub - array of array ; Function to print each of maximal contiguous increasing subarray ; Loop to iterate through the array and print the maximal contiguous increasing subarray . ; Condition to check whether the element at i , is greater than its next neighbouring element or not . ; Driver function
#include <bits/stdc++.h> NEW_LINE using namespace std ; void printmaxSubseq ( int arr [ ] , int n ) { int i ; for ( i = 0 ; i < n ; i ++ ) { if ( arr [ i ] < arr [ i + 1 ] ) cout << arr [ i ] << " ▁ " ; else cout << arr [ i ] << " STRNEWLINE " ; } } int main ( ) { int arr [ ] = { 9 , 8 , 11 , 13 , 10 , 15 , 14 , 16 , 20 , 5 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; printmaxSubseq ( arr , n ) ; return 0 ; }
Count of non decreasing arrays of length N formed with values in range L to R | C ++ implementation of the approach ; Function to return the count of different arrays ; No such combination exists ; Arrays formed with single elements ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int countSum ( int N , int L , int R ) { if ( L > R ) { return 0 ; } if ( N == 1 ) { return R - L + 1 ; } if ( N > 1 ) { return ( N - 2 ) * ( R - L ) + 1 ; } } int main ( ) { int N = 4 , L = 4 , R = 6 ; cout << countSum ( N , L , R ) ; return 0 ; }
Minimum decrement operations to make Array elements equal by only decreasing K each time | C ++ implementation of the above approach ; Finding the minimum element ; Loop over all the elements and find the difference ; Solution found and returned ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; #define lli long long int NEW_LINE lli solve ( lli arr [ ] , lli n , lli k ) { lli i , minx = INT_MAX ; for ( i = 0 ; i < n ; i ++ ) { minx = min ( minx , arr [ i ] ) ; } lli decrements = 0 ; for ( i = 0 ; i < n ; i ++ ) { if ( ( arr [ i ] - minx ) % k != 0 ) { return -1 ; } else { decrements += ( ( arr [ i ] - minx ) / k ) ; } } return decrements ; } int main ( ) { lli n , k ; n = 3 ; k = 3 ; lli arr [ n ] = { 12 , 9 , 15 } ; cout << solve ( arr , n , k ) ; }
Count non decreasing subarrays of size N from N Natural numbers | C ++ program to count non decreasing subarrays of size N from N Natural numbers ; Returns value of Binomial Coefficient C ( n , k ) ; Since nC0 is 1 ; Compute next row of pascal triangle using the previous row ; Function to find the count of required subarrays ; The required count is the binomial coefficient as explained in the approach above ; Driver Function
#include <bits/stdc++.h> NEW_LINE using namespace std ; int binomialCoeff ( int n , int k ) { int C [ k + 1 ] ; memset ( C , 0 , sizeof ( C ) ) ; C [ 0 ] = 1 ; for ( int i = 1 ; i <= n ; i ++ ) { for ( int j = min ( i , k ) ; j > 0 ; j -- ) C [ j ] = C [ j ] + C [ j - 1 ] ; } return C [ k ] ; } int count_of_subarrays ( int N ) { int count = binomialCoeff ( 2 * N - 1 , N ) ; return count ; } int main ( ) { int N = 3 ; cout << count_of_subarrays ( N ) << " STRNEWLINE " ; }
Length of Smallest subarray in range 1 to N with sum greater than a given value | C ++ implementation of the above approach . ; Function to do a binary search on a given range . ; Total sum is the sum of N numbers . ; Sum until mid ; If remaining sum is < the required value , then the required number is in the right half ; Driver code
#include <iostream> NEW_LINE using namespace std ; int usingBinarySearch ( int start , int end , int N , int S ) { if ( start >= end ) return start ; int mid = start + ( end - start ) / 2 ; int totalSum = ( N * ( N + 1 ) ) / 2 ; int midSum = ( mid * ( mid + 1 ) ) / 2 ; if ( ( totalSum - midSum ) <= S ) { return usingBinarySearch ( start , mid , N , S ) ; } return usingBinarySearch ( mid + 1 , end , N , S ) ; } int main ( ) { int N , S ; N = 5 ; S = 11 ; cout << ( N - usingBinarySearch ( 1 , N , N , S ) + 1 ) << endl ; return 0 ; }