text
stringlengths
17
4.49k
code
stringlengths
49
5.46k
Distribution of a Number in Array within a Range | C ++ implementation of the approach ; Function for the distribution of the number ; Distribute the number among k elements ; If there is some remaining sum to distribute ; If there are elements remaining to distribute i . e . ( n - k ) ; Divide the remaining sum into n - k elements ; Print the distribution ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void distribution ( int n , int k , int l , int r , int S , int Sk ) { int a [ n ] ; int len = k , temp , rem , s ; int diff = S - Sk ; for ( int i = 0 ; i < len ; i ++ ) { temp = Sk / k ; rem = Sk % k ; if ( temp + rem >= l && temp + rem <= r ) { a [ i ] = temp ; } else if ( temp + rem > r ) { a [ i ] = r ; } else if ( temp + rem < r ) { cout << " - 1" ; return ; } Sk = Sk - a [ i ] ; k = k - 1 ; } if ( Sk > 0 ) { cout << " - 1" ; return ; } if ( len ) { k = n - len ; for ( int i = len ; i < n ; i ++ ) { temp = diff / k ; rem = diff % k ; if ( temp + rem >= l && temp + rem <= r ) { a [ i ] = temp ; } else if ( temp + rem > r ) { a [ i ] = r ; } else if ( temp + rem < r ) { cout << " - 1" ; return ; } diff = diff - a [ i ] ; k = k - 1 ; } if ( diff ) { cout << " - 1" ; return ; } } for ( int i = 0 ; i < n ; i ++ ) { cout << a [ i ] << " ▁ " ; } } int main ( ) { int n = 5 , k = 3 , l = 1 , r = 5 , S = 13 , Sk = 9 ; distribution ( n , k , l , r , S , Sk ) ; return 0 ; }
Number of valid indices in the permutation of first N natural numbers | C ++ implementation of the approach ; Function to return the number of i 's such that Pi <= Pj for all 1 <= j <= i in the permutation of first N natural numbers ; To store the count of such indices ; Store the mini value ; For all the elements ; Return the required answer ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int min_index ( int p [ ] , int n ) { int ans = 0 ; int mini = INT_MAX ; for ( int i = 0 ; i < n ; i ++ ) { if ( p [ i ] <= mini ) mini = p [ i ] ; if ( mini == p [ i ] ) ans ++ ; } return ans ; } int main ( ) { int P [ ] = { 4 , 2 , 5 , 1 , 3 } ; int n = sizeof ( P ) / sizeof ( int ) ; cout << min_index ( P , n ) ; return 0 ; }
Check if Sum and XOR of all elements of array is equal | C ++ Implementation to Check if Sum and XOR of all Elements of Array is equal ; Function to Check if Sum and XOR of all elements of array is equal ; Sum and XOR of all elements ; Checking Sum and XOR to be equal ; Driver Function ; Check Sum and XOR is equal
#include <iostream> NEW_LINE using namespace std ; int equal_xor_sum ( int arr [ ] , int n ) { int Sum = 0 ; int Xor = 0 ; for ( int i = 0 ; i < n ; i ++ ) { Sum = Sum + arr [ i ] ; Xor = Xor ^ arr [ i ] ; } if ( Sum == Xor ) cout << " YES " ; else cout << " NO " ; return 0 ; } int main ( ) { int arr [ ] = { 6 , 3 , 7 , 10 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; equal_xor_sum ( arr , n ) ; return 0 ; }
Count of odd length contiguous Palindromic sequences in a Matrix | C ++ code to Count the odd length contiguous Palindromic sequences in the matrix ; Function to count the number of contiguous palindromic sequences in the matrix ; Add the total number of elements in the matrix to the count ; Length of possible sequence to be checked for palindrome horizontally and vertically ; Iterate through each element of the matrix and count the number of palindromic sequences in each row and column ; Find the possible length of sequences that can be a palindrome ; From i , check if the sequence formed by elements to its left and right is palindrome or not ; if the sequence [ i , j - k ] to [ i , j + k ] is a palindrome , increment the count by 1 ; From i , check if the sequence formed by elements to its above and below is palindrome or not ; if the sequence [ i - k , j ] to [ i + k , j ] is a palindrome , increment the count by 1 ; Return the total count of the palindromic sequences ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; #define MAX 10 NEW_LINE int countPalindromes ( int n , int m , int matrix [ MAX ] [ MAX ] ) { int count = n * m ; int length_of_sequence_row ; int length_of_sequence_column ; for ( int i = 0 ; i < n ; i ++ ) { for ( int j = 0 ; j < m ; j ++ ) { length_of_sequence_row = min ( j , m - 1 - j ) ; length_of_sequence_column = min ( i , n - i - 1 ) ; for ( int k = 1 ; k <= length_of_sequence_row ; k ++ ) { if ( matrix [ i ] [ j - k ] == matrix [ i ] [ j + k ] ) { count ++ ; } else { break ; } } for ( int k = 1 ; k <= length_of_sequence_column ; k ++ ) { if ( matrix [ i - k ] [ j ] == matrix [ i + k ] [ j ] ) { count ++ ; } else { break ; } } } } return count ; } int main ( void ) { int m = 3 , n = 3 ; int matrix [ MAX ] [ MAX ] = { { 2 , 1 , 2 } , { 1 , 1 , 1 } , { 2 , 1 , 2 } } ; cout << countPalindromes ( n , m , matrix ) << endl ; return 0 ; }
Reduce a number to 1 by performing given operations | Set 2 | C ++ implementation of the approach ; Function to return the number of set bits in n ; Function to return the minimum steps required to reach 1 ; If n is even then divide it by 2 ; If n is 3 or the number of set bits in ( n - 1 ) is less than the number of set bits in ( n + 1 ) ; Increment the number of steps ; Return the minimum number of steps ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int set_bits ( int n ) { int count = 0 ; while ( n ) { count += n % 2 ; n /= 2 ; } return count ; } int minSteps ( int n ) { int ans = 0 ; while ( n != 1 ) { if ( n % 2 == 0 ) n /= 2 ; else if ( n == 3 or set_bits ( n - 1 ) < set_bits ( n + 1 ) ) n -- ; else n ++ ; ans ++ ; } return ans ; } int main ( ) { int n = 15 ; cout << minSteps ( n ) ; return 0 ; }
Minimum integer that can be obtained by swapping adjacent digits of different parity | C ++ implementation of the above approach . ; Function to return the minimum number ; Store the elements which are divisible by two in stack1 ; Store the elements which are not divisible by two in stack2 . ; Concatenate the answer with smaller value of the topmost elements of both the stacks and then pop that element ; Concatenate the answer with remaining values of stack1 . ; Concatenate the answer with remaining values of stack2 . ; Driver code ; Function calling
#include <bits/stdc++.h> NEW_LINE using namespace std ; int minimumNo ( int n ) { int ans = 0 ; stack < int > stack1 ; stack < int > stack2 ; while ( n != 0 ) { int r = n % 10 ; if ( r % 2 == 0 ) { stack1 . push ( r ) ; } else { stack2 . push ( r ) ; } n = n / 10 ; } while ( ! stack1 . empty ( ) && ! stack2 . empty ( ) ) { if ( stack1 . top ( ) < stack2 . top ( ) ) { ans = ans * 10 + stack1 . top ( ) ; stack1 . pop ( ) ; } else { ans = ans * 10 + stack2 . top ( ) ; stack2 . pop ( ) ; } } while ( ! stack1 . empty ( ) ) { ans = ans * 10 + stack1 . top ( ) ; stack1 . pop ( ) ; } while ( ! stack2 . empty ( ) ) { ans = ans * 10 + stack2 . top ( ) ; stack2 . pop ( ) ; } return ans ; } int main ( ) { int n1 = 64432 ; cout << minimumNo ( n1 ) << endl ; int n2 = 3137 ; cout << minimumNo ( n2 ) << endl ; return 0 ; }
Count of possible arrays from prefix | C ++ implementation of the above approach ; Function to find power of a number . ; Function to find factorial of a number . ; Function to print no of arrays ; c variable counts the no of pairs ; Map to store the frequency of each element ; Sum of all elements of the array ; Variable to check if it is possible to make any array ; First element of suffix array and the last element of prefix array ; Check if the element exists in the map ; If elements of any pair are equal and their frequency is not divisible by 2 update the isArrayPossible variable to false and break through the loop ; If elements of any pair are not equal and their frequency is not same update the isArrayPossible variable to false and break through the loop ; Check if frequency is greater than zero ; update the count of pairs ; Multiply the answer by 2 ^ ( frequency of pairs ) since the elements of the pair are not the same in this condition ; Divide the answer by the factorial of no of similar pairs ; Make frequency of both these elements 0 ; Update the count of pairs ; Divide the answer by the factorial of no . of similar pairs ; Make frequency of this element 0 ; Check if it is possible to make the array and there are n - 1 pairs whose sum will be equal to s1 ; Driver code ; Function calling
#include <bits/stdc++.h> NEW_LINE using namespace std ; int power ( int a , int b ) { int result = 1 ; while ( b > 0 ) { if ( b % 2 == 1 ) { result = result * a ; } a = a * a ; b = b / 2 ; } return result ; } int factorial ( int n ) { int fact = 1 ; for ( int i = 1 ; i <= n ; i ++ ) { fact = fact * i ; } return fact ; } void findNoOfArrays ( int * a , int n ) { int sum = 0 , s1 , c = 0 ; map < int , int > mp ; for ( int i = 0 ; i < 2 * n ; i ++ ) { mp [ a [ i ] ] ++ ; sum = sum + a [ i ] ; } bool isArrayPossible = true ; int ans = factorial ( n - 1 ) ; s1 = sum / ( n + 1 ) ; if ( mp [ s1 ] >= 2 ) { mp [ s1 ] = mp [ s1 ] - 2 ; } else { isArrayPossible = false ; } if ( isArrayPossible ) { for ( auto i : mp ) { if ( i . first == s1 - i . first ) { if ( mp [ i . first ] % 2 != 0 ) { isArrayPossible = false ; break ; } } if ( i . first != s1 - i . first ) { if ( mp [ i . first ] != mp [ s1 - i . first ] ) { isArrayPossible = false ; break ; } } if ( i . second > 0 ) { if ( i . first != s1 - i . first ) { c = c + i . second ; ans = ans * power ( 2 , i . second ) ; ans = ans / factorial ( i . second ) ; mp [ i . first ] = 0 ; mp [ s1 - i . first ] = 0 ; } if ( i . first == s1 - i . first ) { c = c + i . second / 2 ; ans = ans / factorial ( i . second / 2 ) ; mp [ i . first ] = 0 ; } } } } if ( c < n - 1 isArrayPossible == false ) { cout << "0" << endl ; } else { cout << ans << endl ; } } int main ( ) { int arr1 [ ] = { 5 , 2 , 3 , 5 } ; int n1 = sizeof ( arr1 ) / sizeof ( arr1 [ 0 ] ) ; findNoOfArrays ( arr1 , n1 / 2 ) ; int arr2 [ ] = { -1 , -1 , -1 , 0 , 1 , 0 , 1 , 0 , 1 , 0 , 0 , 0 } ; int n2 = sizeof ( arr2 ) / sizeof ( arr2 [ 0 ] ) ; findNoOfArrays ( arr2 , n2 / 2 ) ; return 0 ; }
Find two numbers with the given LCM and minimum possible difference | C ++ implementation of the approach ; Function to return the LCM of a and b ; Function to find and print the two numbers ; To find the factors ; To check if i is a factor of x and the minimum possible number satisfying the given conditions ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int lcm ( int a , int b ) { return ( a / __gcd ( a , b ) * b ) ; } void findNums ( int x ) { int ans ; for ( int i = 1 ; i <= sqrt ( x ) ; i ++ ) { if ( x % i == 0 && lcm ( i , x / i ) == x ) { ans = i ; } } cout << ans << " ▁ " << ( x / ans ) ; } int main ( ) { int x = 12 ; findNums ( x ) ; return 0 ; }
Find an integer that is common in the maximum number of given arithmetic progressions | C ++ implementation of the approach ; Function to return element common in maximum number of APs ; Initialize the count variable ; Increment count for every element of an AP ; Find the index with maximum count ; Return the maximum common element ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; #define MAXN 1000000 NEW_LINE int maxCommonElement ( int A [ ] , int D [ ] , int N ) { int cnt [ MAXN ] = { 0 } ; for ( int i = 0 ; i < N ; i ++ ) { for ( int j = A [ i ] ; j < MAXN ; j += D [ i ] ) cnt [ j ] ++ ; } int com = max_element ( cnt , cnt + MAXN ) - cnt ; return com ; } int main ( ) { int A [ ] = { 13 , 1 , 2 , 5 } , D [ ] = { 5 , 10 , 1 , 12 } ; int N = sizeof ( A ) / sizeof ( A [ 0 ] ) ; cout << maxCommonElement ( A , D , N ) ; return 0 ; }
Number of trailing zeros in N * ( N | C ++ implementation of the approach ; Function to return the count of trailing 0 s in the given function ; If n is odd ; If n is even ; Find the trailing zeros in n / 2 factorial ; Return the required answer ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int findTrailingZeros ( int n ) { if ( n & 1 ) return 0 ; else { int ans = 0 ; n /= 2 ; while ( n ) { ans += n / 5 ; n /= 5 ; } return ans ; } } int main ( ) { int n = 12 ; cout << findTrailingZeros ( n ) ; return 0 ; }
Divide N into K unique parts such that gcd of those parts is maximum | C ++ implementation of the approach ; Function to calculate maximum GCD ; Minimum possible sum for K unique positive integers ; It is not possible to divide N into K unique parts ; All the factors greater than sqrt ( N ) are complementary of the factors less than sqrt ( N ) ; If i is a factor of N ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int maxGCD ( int N , int K ) { int minSum = ( K * ( K + 1 ) ) / 2 ; if ( N < minSum ) return -1 ; int i = sqrt ( N ) ; int res = 1 ; while ( i >= 1 ) { if ( N % i == 0 ) { if ( i >= minSum ) res = max ( res , N / i ) ; if ( N / i >= minSum ) res = max ( res , i ) ; } i -- ; } return res ; } int main ( ) { int N = 18 , K = 3 ; cout << maxGCD ( N , K ) ; return 0 ; }
Radius of the inscribed circle within three tangent circles | C ++ implementation of the approach ; Radius of the 3 given circles declared as double . ; Calculation of area of a triangle by Heron 's formula ; Applying binary search to find the radius r4 of the required circle ; Area of main triangle ; Loop runs until l and h becomes approximately equal ; Area of smaller triangles ; If sum of smaller triangles is less than main triangle ; If sum of smaller triangles is greater than or equal to main triangle ; Driver code ; Taking r1 , r2 , r3 as input ; Call to function binary search
#include <bits/stdc++.h> NEW_LINE using namespace std ; double r1 , r2 , r3 ; double area ( double a , double b , double c ) { double p = ( a + b + c ) / 2 ; return sqrt ( p ) * sqrt ( p - a ) * sqrt ( p - b ) * sqrt ( p - c ) ; } double binary_search ( ) { double s = area ( r1 + r2 , r2 + r3 , r3 + r1 ) ; double l = 0 , h = s / ( r1 + r2 + r3 ) ; while ( h - l >= 1.e-7 ) { double mid = ( l + h ) / 2 ; double s1 = area ( mid + r1 , mid + r2 , r1 + r2 ) ; double s2 = area ( mid + r1 , mid + r3 , r1 + r3 ) ; double s3 = area ( mid + r2 , mid + r3 , r2 + r3 ) ; if ( s1 + s2 + s3 < s ) { l = mid ; } else { h = mid ; } } return ( l + h ) / 2 ; } int main ( ) { r1 = 1.0 ; r2 = 2.0 ; r3 = 3.0 ; cout << fixed << setprecision ( 6 ) << binary_search ( ) << endl ; return 0 ; }
Radius of the inscribed circle within three tangent circles | C ++ implementation of the approach ; Driver code ; Radius of the 3 given circles declared as double . ; Taking r1 , r2 , r3 as input ; Calculation of r4 using formula given above
#include <bits/stdc++.h> NEW_LINE using namespace std ; int main ( ) { double r1 , r2 , r3 ; r1 = 1 ; r2 = 2 ; r3 = 3 ; double r4 = ( r1 * r2 * r3 ) / ( r1 * r2 + r2 * r3 + r1 * r3 + 2.0 * sqrt ( r1 * r2 * r3 * ( r1 + r2 + r3 ) ) ) ; cout << fixed << setprecision ( 6 ) << r4 << ' ' ; return 0 ; }
Make all elements zero by decreasing any two elements by one at a time | C ++ implementation of the approach ; Function that returns true if all the array elements can be made 0 with the given operation ; Find the maximum element and the sum ; Check the required condition ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool checkZeroArray ( int * arr , int n ) { int sum = 0 , maximum = INT_MIN ; for ( int i = 0 ; i < n ; i ++ ) { sum = sum + arr [ i ] ; maximum = max ( maximum , arr [ i ] ) ; } if ( sum % 2 == 0 && maximum <= sum / 2 ) return true ; return false ; } int main ( ) { int arr [ ] = { 1 , 2 , 1 , 2 , 2 } ; int n = sizeof ( arr ) / sizeof ( int ) ; if ( checkZeroArray ( arr , n ) ) cout << " Yes " ; else cout << " No " ; return 0 ; }
Subarray permutation that satisfies the given condition | C ++ implementation of the approach ; Function that returns true if the required subarray exists in the given array ; Map to store the positions of each integer in the original permutation ; To store the address of each entry in arr [ n ] but with 1 - based indexing ; To track minimum position sumcur for sum of all positions till this position ; Summing up addresses ; Tracking minimum address encountered till now ; The sum of the addresses if it forms the required subarray ; If current sum of address is equal to val ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; typedef long long int ll ; bool subArray ( ll * arr , ll n , ll m ) { ll i ; unordered_map < ll , ll > mp ; for ( i = 0 ; i < n ; i ++ ) { mp [ arr [ i ] ] = i + 1 ; } ll sumcur = 0 ; ll p = INT_MAX ; vector < ll > ans ; for ( i = 1 ; i <= m ; i ++ ) { sumcur += mp [ i ] ; p = min ( p , mp [ i ] ) ; ll val = p * i - i + ( i * ( i + 1 ) ) / 2 ; if ( i == m ) { if ( val == sumcur ) { return true ; } else return false ; } } } int main ( ) { ll arr [ ] = { 4 , 5 , 1 , 3 , 2 , 6 } ; int n = sizeof ( arr ) / sizeof ( int ) ; ll m = 3 ; if ( subArray ( arr , n , m ) ) cout << " Yes " ; else cout << " No " ; return 0 ; }
Sum of all N digit palindrome numbers | C ++ program for the above approach ; Function to check palindrome ; Function to calculate the sum of n - digit palindrome ; Run a loop to check all possible palindrome ; If palindrome append sum ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool isPalindrome ( string & s ) { int left = 0 , right = s . size ( ) - 1 ; while ( left <= right ) { if ( s [ left ] != s [ right ] ) { return false ; } left ++ ; right -- ; } return true ; } long long getSum ( int n ) { int start = pow ( 10 , n - 1 ) ; int end = pow ( 10 , n ) - 1 ; long long sum = 0 ; for ( int i = start ; i <= end ; i ++ ) { string s = to_string ( i ) ; if ( isPalindrome ( s ) ) { sum += i ; } } return sum ; } int main ( ) { int n = 1 ; long long ans = getSum ( n ) ; cout << ans << ' ' ; return 0 ; }
Sum of all N digit palindrome numbers | C ++ program for the above approach ; Function to calculate sum of n digit number ; Corner case ; Using above approach ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; long double getSum ( int n ) { long double sum = 0 ; if ( n == 1 ) { sum = 45.0 ; } else { sum = ( 99.0 / 2.0 ) * pow ( 10 , n - 1 ) * pow ( 10 , ( n - 1 ) / 2 ) ; } return sum ; } int main ( ) { int n = 3 ; long double ans = getSum ( n ) ; cout << setprecision ( 12 ) << ans << ' ' ; return 0 ; }
Longest sub | C ++ implementation of the approach ; Function to return the length of the largest subarray with maximum possible GCD ; To store the maximum number present in the array ; Finding the maximum element ; To store the final answer ; Two pointer ; Running a loop from j = i ; Condition for incrementing ' j ' ; Updating the answer ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int findLength ( int * arr , int n ) { int x = 0 ; for ( int i = 0 ; i < n ; i ++ ) x = max ( x , arr [ i ] ) ; int ans = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( arr [ i ] != x ) continue ; int j = i ; while ( arr [ j ] == x ) j ++ ; ans = max ( ans , j - i ) ; } return ans ; } int main ( ) { int arr [ ] = { 1 , 2 , 2 } ; int n = sizeof ( arr ) / sizeof ( int ) ; cout << findLength ( arr , n ) ; return 0 ; }
Count number of pairs ( i , j ) such that arr [ i ] * arr [ j ] = arr [ i ] + arr [ j ] | C ++ program to count pairs ( i , j ) such that arr [ i ] * arr [ j ] = arr [ i ] + arr [ j ] ; Function to return the count of pairs ( i , j ) such that arr [ i ] * arr [ j ] = arr [ i ] + arr [ j ] ; Increment count if condition satisfy ; Return count of pairs ; Driver code ; Get and print count of pairs
#include <bits/stdc++.h> NEW_LINE using namespace std ; long countPairs ( int arr [ ] , int n ) { long count = 0 ; for ( int i = 0 ; i < n - 1 ; i ++ ) { for ( int j = i + 1 ; j < n ; j ++ ) { if ( arr [ i ] * arr [ j ] == arr [ i ] + arr [ j ] ) count ++ ; } } return count ; } int main ( ) { int arr [ ] = { 2 , 0 , 3 , 2 , 0 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << countPairs ( arr , n ) ; return 0 ; }
Count number of pairs ( i , j ) such that arr [ i ] * arr [ j ] = arr [ i ] + arr [ j ] | C ++ program to count pairs ( i , j ) such that arr [ i ] * arr [ j ] = arr [ i ] + arr [ j ] ; Function to return the count of pairs ( i , j ) such that arr [ i ] * arr [ j ] = arr [ i ] + arr [ j ] ; Count number of 0 ' s ▁ and ▁ 2' s in the array ; Total pairs due to occurrence of 0 's ; Total pairs due to occurrence of 2 's ; Return count of all pairs ; Driver code ; Get and print count of pairs
#include <bits/stdc++.h> NEW_LINE using namespace std ; long countPairs ( int arr [ ] , int n ) { int countZero = 0 ; int countTwo = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( arr [ i ] == 0 ) countZero ++ ; else if ( arr [ i ] == 2 ) countTwo ++ ; } long pair0 = ( countZero * ( countZero - 1 ) ) / 2 ; long pair2 = ( countTwo * ( countTwo - 1 ) ) / 2 ; return pair0 + pair2 ; } int main ( ) { int arr [ ] = { 2 , 0 , 3 , 2 , 0 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << countPairs ( arr , n ) ; return 0 ; }
Number of subsequences with positive product | C ++ implementation of the approach ; Function to return the count of all the subsequences with positive product ; To store the count of positive elements in the array ; To store the count of negative elements in the array ; If the current element is positive ; If the current element is negative ; For all the positive elements of the array ; For all the negative elements of the array ; For the empty subsequence ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int cntSubSeq ( int arr [ ] , int n ) { int pos_count = 0 ; int neg_count = 0 ; int result ; for ( int i = 0 ; i < n ; i ++ ) { if ( arr [ i ] > 0 ) pos_count ++ ; if ( arr [ i ] < 0 ) neg_count ++ ; } result = pow ( 2 , pos_count ) ; if ( neg_count > 0 ) result *= pow ( 2 , neg_count - 1 ) ; result -= 1 ; return result ; } int main ( ) { int arr [ ] = { 2 , -3 , -1 , 4 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << cntSubSeq ( arr , n ) ; return 0 ; }
Smallest number dividing minimum number of elements in the array | Set 2 | C ++ implementation of the approach ; Function to return the smallest number that divides minimum number of elements in the given array ; m stores the maximum in the array ; Frequency array ; Sieve ; Incrementing j ; If no multiples of j are in the array ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int findMin ( int * arr , int n ) { int m = 0 ; for ( int i = 0 ; i < n ; i ++ ) m = max ( m , arr [ i ] ) ; int freq [ m + 2 ] = { 0 } ; for ( int i = 0 ; i < n ; i ++ ) freq [ arr [ i ] ] ++ ; for ( int i = 1 ; i <= m + 1 ; i ++ ) { int j = i ; int cnt = 0 ; while ( j <= m ) { cnt += freq [ j ] ; j += i ; } if ( ! cnt ) return i ; } return m + 1 ; } int main ( ) { int arr [ ] = { 2 , 12 , 6 } ; int n = sizeof ( arr ) / sizeof ( int ) ; cout << findMin ( arr , n ) ; return 0 ; }
Smallest number dividing minimum number of elements in the Array | C ++ implementation of the approach ; Function to return the smallest number that divides minimum number of elements ; m stores the maximum in the array ; Frequency table ; Loop to factorize ; sqrt factorization of the numbers ; Finding the smallest number with zero multiples ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int findMin ( int * arr , int n ) { int m = 0 ; for ( int i = 0 ; i < n ; i ++ ) m = max ( m , arr [ i ] ) ; int cnt [ m + 2 ] = { 0 } ; for ( int i = 0 ; i < n ; i ++ ) { for ( int j = 1 ; j * j <= arr [ i ] ; j ++ ) { if ( arr [ i ] % j == 0 ) { if ( j * j == arr [ i ] ) cnt [ j ] ++ ; else cnt [ j ] ++ , cnt [ arr [ i ] / j ] ++ ; } } } for ( int i = 1 ; i <= m + 1 ; i ++ ) if ( cnt [ i ] == 0 ) { return i ; } return -1 ; } int main ( ) { int arr [ ] = { 2 , 12 , 6 } ; int n = sizeof ( arr ) / sizeof ( int ) ; cout << findMin ( arr , n ) ; return 0 ; }
Remove two consecutive integers from 1 to N to make sum equal to S | C ++ program remove two consecutive integers from 1 to N to make sum equal to S ; Function to find the numbers to be removed ; typecast appropriately so that answer is float ; return the obtained result ; Convert i to integer ; If i is an integer is 0 then answer is Yes ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; float findNumber ( int N , int S ) { float i = ( ( ( float ) ( N ) * ( float ) ( N + 1 ) ) / 4 ) - ( ( float ) ( S + 1 ) / 2 ) ; return i ; } void check ( int N , int S ) { float i = findNumber ( N , S ) ; int integerI = ( int ) i ; if ( i - integerI == 0 ) cout << " Yes : ▁ " << integerI << " , ▁ " << integerI + 1 << endl ; else cout << " No " << endl ; } int main ( ) { int N = 4 , S = 3 ; check ( N , S ) ; N = 5 , S = 3 ; check ( N , S ) ; return 0 ; }
Remove all the prime numbers from the given array | C ++ implementation of the approach ; Function for Sieve of Eratosthenes ; Function to print the elements of the array ; Function to remove all the prime numbers ; Generate primes ; Traverse the array ; If the current element is prime ; Shift all the elements on the right of it to the left ; Decrease the loop counter by 1 to check the shifted element ; Decrease the length ; Print the updated array ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; const int sz = 1e5 ; bool isPrime [ sz + 1 ] ; void sieve ( ) { memset ( isPrime , true , sizeof ( isPrime ) ) ; isPrime [ 0 ] = isPrime [ 1 ] = false ; for ( int i = 2 ; i * i <= sz ; i ++ ) { if ( isPrime [ i ] ) { for ( int j = i * i ; j < sz ; j += i ) { isPrime [ j ] = false ; } } } } void printArray ( int arr [ ] , int len ) { for ( int i = 0 ; i < len ; i ++ ) { cout << arr [ i ] << ' ▁ ' ; } } void removePrimes ( int arr [ ] , int len ) { sieve ( ) ; for ( int i = 0 ; i < len ; i ++ ) { if ( isPrime [ arr [ i ] ] ) { for ( int j = i ; j < len ; j ++ ) { arr [ j ] = arr [ j + 1 ] ; } i -- ; len -- ; } } printArray ( arr , len ) ; } int main ( ) { int arr [ ] = { 4 , 6 , 5 , 3 , 8 , 7 , 10 , 11 , 14 , 15 } ; int len = sizeof ( arr ) / sizeof ( int ) ; removePrimes ( arr , len ) ; return 0 ; }
Remove one element to get minimum OR value | C ++ implementation of the approach ; Function to return the minimized OR after removing an element from the array ; Base case ; Prefix and suffix OR array ; Computing prefix / suffix OR arrays ; To store the final answer ; Finding the final answer ; Returning the final answer ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int minOR ( int * arr , int n ) { if ( n == 1 ) return 0 ; int pre [ n ] , suf [ n ] ; pre [ 0 ] = arr [ 0 ] , suf [ n - 1 ] = arr [ n - 1 ] ; for ( int i = 1 ; i < n ; i ++ ) pre [ i ] = ( pre [ i - 1 ] arr [ i ] ) ; for ( int i = n - 2 ; i >= 0 ; i -- ) suf [ i ] = ( suf [ i + 1 ] arr [ i ] ) ; int ans = min ( pre [ n - 2 ] , suf [ 1 ] ) ; for ( int i = 1 ; i < n - 1 ; i ++ ) ans = min ( ans , ( pre [ i - 1 ] suf [ i + 1 ] ) ) ; return ans ; } int main ( ) { int arr [ ] = { 1 , 2 , 3 } ; int n = sizeof ( arr ) / sizeof ( int ) ; cout << minOR ( arr , n ) ; return 0 ; }
Check if there exists a prime number which gives Y after being repeatedly subtracted from X | C ++ implementation of the approach ; Function that returns true if any prime number satisfies the given conditions ; No such prime exists ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool isPossible ( int x , int y ) { if ( ( x - y ) == 1 ) return false ; return true ; } int main ( ) { int x = 100 , y = 98 ; if ( isPossible ( x , y ) ) cout << " Yes " ; else cout << " No " ; return 0 ; }
Find number of square of area Z which can be built in a matrix having blocked regions | C ++ implementation of the approach ; Function to calculate the number of square areas of size K * K ; Row array and column array to store the lengths of differences between consecutive rows / columns ; Fill the conrow vector ; Fill the concol vector ; To store the required answer ; Every pair of row size and column size would result in an unblocked region ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int subgrids ( int N , int Z , int row [ ] , int col [ ] , int r , int c ) { vector < int > conrow ; vector < int > concol ; int K = sqrt ( Z ) ; conrow . push_back ( row [ 0 ] - 0 - 1 ) ; conrow . push_back ( N + 1 - row [ r - 1 ] - 1 ) ; for ( int i = 1 ; i < r ; i ++ ) { conrow . push_back ( row [ i ] - row [ i - 1 ] - 1 ) ; } concol . push_back ( col [ 0 ] - 0 - 1 ) ; concol . push_back ( N + 1 - col - 1 ) ; for ( int i = 1 ; i < c ; i ++ ) { concol . push_back ( col [ i ] - col [ i - 1 ] - 1 ) ; } int row_size = conrow . size ( ) ; int col_size = concol . size ( ) ; int answer = 0 ; for ( int i = 0 ; i < row_size ; i ++ ) { for ( int j = 0 ; j < col_size ; j ++ ) { int total = ( concol [ j ] / K ) * ( conrow [ i ] / K ) ; answer += ( total ) ; } } return answer ; } int main ( ) { int N = 8 , Z = 4 ; int row [ ] = { 4 , 6 } ; int col [ ] = { 3 , 8 } ; int r = sizeof ( row ) / sizeof ( row [ 0 ] ) ; int c = sizeof ( col ) / sizeof ( col [ 0 ] ) ; cout << subgrids ( N , Z , row , col , r , c ) ; return 0 ; }
Count of numbers whose sum of increasing powers of digits is equal to the number itself | C ++ implementation of the approach ; Function to return the count of digits of n ; Function to return the sum of increasing powers of N ; To store the required answer ; Count of digits in n which will be the power of the last digit ; While there are digits left ; Get the last digit ; Add the last digit after raising it to the required power ; Decrement the power for the previous digit ; Remove the last digit ; Function to return the count of integers which satisfy the given conditions ; If current element satisfies the given condition ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int countDigits ( int n ) { int cnt = 0 ; while ( n > 0 ) { cnt ++ ; n /= 10 ; } return cnt ; } int digitPowSum ( int n ) { int sum = 0 ; int pw = countDigits ( n ) ; while ( n > 0 ) { int d = n % 10 ; sum += pow ( d , pw ) ; pw -- ; n /= 10 ; } return sum ; } int countNum ( int n ) { int count = 0 ; for ( int i = 0 ; i <= n ; i ++ ) { if ( i == digitPowSum ( i ) ) { count ++ ; } } return count ; } int main ( ) { int n = 200 ; cout << countNum ( n ) ; return 0 ; }
Print all perfect squares from the given range | C ++ implementation of the approach ; Function to print all the perfect squares from the given range ; For every element from the range ; If current element is a perfect square ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void perfectSquares ( float l , float r ) { for ( int i = l ; i <= r ; i ++ ) { if ( sqrt ( i ) == ( int ) sqrt ( i ) ) cout << i << " ▁ " ; } } int main ( ) { int l = 2 , r = 24 ; perfectSquares ( l , r ) ; return 0 ; }
Print all perfect squares from the given range | C ++ implementation of the approach ; Function to print all the perfect squares from the given range ; Getting the very first number ; First number 's square ; Next number is at the difference of ; While the perfect squares are from the range ; Print the perfect square ; Get the next perfect square ; Next odd number to be added ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void perfectSquares ( float l , float r ) { int number = ceil ( sqrt ( l ) ) ; int n2 = number * number ; number = ( number * 2 ) + 1 ; while ( ( n2 >= l && n2 <= r ) ) { cout << n2 << " ▁ " ; n2 = n2 + number ; number += 2 ; } } int main ( ) { int l = 2 , r = 24 ; perfectSquares ( l , r ) ; return 0 ; }
Find the value of N XOR 'ed to itself K times | C ++ implementation of the approach ; Function to return n ^ n ^ ... k times ; Find the result ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int xorK ( int n , int k ) { int res = n ; for ( int i = 1 ; i < k ; i ++ ) res = ( res ^ n ) ; return res ; } int main ( ) { int n = 123 , k = 3 ; cout << xorK ( n , k ) ; return 0 ; }
Find all the possible remainders when N is divided by all positive integers from 1 to N + 1 | C ++ implementation of the approach ; Function to find all the distinct remainders when n is divided by all the elements from the range [ 1 , n + 1 ] ; Set will be used to store the remainders in order to eliminate duplicates ; Find the remainders ; Print the contents of the set ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; typedef long long int ll ; void findRemainders ( ll n ) { set < ll > vc ; for ( ll i = 1 ; i <= ceil ( sqrt ( n ) ) ; i ++ ) vc . insert ( n / i ) ; for ( ll i = n / ceil ( sqrt ( n ) ) - 1 ; i >= 0 ; i -- ) vc . insert ( i ) ; for ( auto it : vc ) cout << it << " ▁ " ; } int main ( ) { ll n = 5 ; findRemainders ( n ) ; return 0 ; }
Count of primes below N which can be expressed as the sum of two primes | C ++ implementation of the approach ; Function for Sieve of Eratosthenes ; false here indicates that it is not prime ; If prime [ p ] is not changed , then it is a prime ; Update all multiples of p , set them to non - prime ; Function to return the count of primes less than or equal to n which can be expressed as the sum of two primes ; To store the required count ; If the integer is prime and it can be expressed as the sum of 2 and a prime number ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; const int MAX = 100005 ; bool prime [ MAX ] ; void SieveOfEratosthenes ( ) { memset ( prime , true , sizeof ( prime ) ) ; prime [ 0 ] = false ; prime [ 1 ] = false ; for ( int p = 2 ; p * p <= MAX ; p ++ ) { if ( prime [ p ] ) { for ( int i = p * 2 ; i <= MAX ; i += p ) prime [ i ] = false ; } } } int countPrimes ( int n ) { SieveOfEratosthenes ( ) ; int cnt = 0 ; for ( int i = 2 ; i < n ; i ++ ) { if ( prime [ i ] && prime [ i - 2 ] ) cnt ++ ; } return cnt ; } int main ( ) { int n = 11 ; cout << countPrimes ( n ) ; return 0 ; }
Print all palindrome dates between the given years | C ++ implementation of the approach ; Returns true if given year is valid ; Return true if year is a multiple pf 4 and not multiple of 100. OR year is multiple of 400. ; Returns true if given year is valid or not . ; If year , month and day are not in given range ; Handle February month with leap year ; Months of April , June , Sept and Nov must have number of days less than or equal to 30. ; Function to print the palindrome dates between the given years ; For every year ; Current year as a string ; To store the reverse of year ; Get the day and the month ; If the current palindrome date is valid ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; const int MAX_VALID_YR = 9999 ; const int MIN_VALID_YR = 1800 ; bool isLeap ( int year ) { return ( ( ( year % 4 == 0 ) && ( year % 100 != 0 ) ) || ( year % 400 == 0 ) ) ; } bool isValidDate ( int d , int m , int y ) { if ( y > MAX_VALID_YR y < MIN_VALID_YR ) return false ; if ( m < 1 m > 12 ) return false ; if ( d < 1 d > 31 ) return false ; if ( m == 2 ) { if ( isLeap ( y ) ) return ( d <= 29 ) ; else return ( d <= 28 ) ; } if ( m == 4 m == 6 m == 9 m == 11 ) return ( d <= 30 ) ; return true ; } void printPalindromeDates ( int y1 , int y2 ) { for ( int year = y1 ; year <= y2 ; year ++ ) { string str = to_string ( year ) ; string rev = str ; reverse ( rev . begin ( ) , rev . end ( ) ) ; int day = stoi ( rev . substr ( 0 , 2 ) ) ; int month = stoi ( rev . substr ( 2 , 2 ) ) ; if ( isValidDate ( day , month , year ) ) { cout << rev << str << endl ; } } } int main ( ) { int y1 = 2001 , y2 = 2005 ; printPalindromeDates ( y1 , y2 ) ; return 0 ; }
Find an integer in the given range that satisfies the given conditions | C ++ implementation of the approach ; Function that returns true if x contains all distinct digits ; Last digit of x ; If current digit has appeared before ; Mark the current digit to present ; Remove the last digit ; Function to return the required value of k ; To store the maximum value for the given expression ; If i contains all distinct digits ; If the value of the expression is also maximum then update k and the expression ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; const int MAX = 10 ; bool distinctDigits ( int x ) { bool present [ MAX ] = { false } ; while ( x > 0 ) { int digit = x % 10 ; if ( present [ digit ] ) return false ; present [ digit ] = true ; x /= 10 ; } return true ; } int findK ( int l , int r ) { int maxExp = INT_MIN ; int k = -1 ; for ( int i = l ; i <= r ; i ++ ) { if ( distinctDigits ( i ) ) { int exp = ( l - i ) * ( i - r ) ; if ( exp >= maxExp ) { k = i ; maxExp = exp ; } } } return k ; } int main ( ) { int l = 50 , r = 60 ; cout << findK ( l , r ) ; return 0 ; }
Restore a permutation from the given helper array | C ++ implementation of the approach ; Function to find the required permutation ; Each element in P ' is like a cumulative sum in Q ; minval is the minimum value in P ' ; To check if each entry in P is from the range [ 1 , n ] ; Invalid permutation ; If a valid permutation exists ; Print the permutation ; No valid permutation ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void findPerm ( int Q [ ] , int n ) { int minval = 0 , qsum = 0 ; for ( int i = 0 ; i < n - 1 ; i ++ ) { qsum += Q [ i ] ; if ( qsum < minval ) minval = qsum ; } vector < int > P ( n ) ; P [ 0 ] = 1 - minval ; bool permFound = true ; for ( int i = 0 ; i < n - 1 ; i ++ ) { P [ i + 1 ] = P [ i ] + Q [ i ] ; if ( P [ i + 1 ] > n P [ i + 1 ] < 1 ) { permFound = false ; break ; } } if ( permFound ) { for ( int i = 0 ; i < n ; i ++ ) { cout << P [ i ] << " ▁ " ; } } else { cout << -1 ; } } int main ( ) { int Q [ ] = { -2 , 1 } ; int n = 1 + ( sizeof ( Q ) / sizeof ( int ) ) ; findPerm ( Q , n ) ; return 0 ; }
Convert Decimal To Hexa | C ++ program to convert decimal to hexadecimal covering negative numbers ; Function to convert decimal no . to hexadecimal number ; map for decimal to hexa , 0 - 9 are straightforward , alphabets a - f used for 10 to 15. ; string to be returned ; check if num is 0 and directly return "0" ; if num > 0 , use normal technique as discussed in other post ; if num < 0 , we need to use the elaborated trick above , lets see this ; store num in a u_int , size of u_it is greater , it will be positive since msb is 0 ; use the same remainder technique . ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; string Hex ( int num ) { map < int , char > m ; char digit = '0' ; char c = ' a ' ; for ( int i = 0 ; i <= 15 ; i ++ ) { if ( i < 10 ) { m [ i ] = digit ++ ; } else { m [ i ] = c ++ ; } } string res = " " ; if ( ! num ) { return "0" ; } if ( num > 0 ) { while ( num ) { res = m [ num % 16 ] + res ; num /= 16 ; } } else { u_int n = num ; while ( n ) { res = m [ n % 16 ] + res ; n /= 16 ; } } return res ; } int main ( ) { int x = 134 , y = -1 , z = -234 ; cout << " Hexa ▁ representation ▁ for " << endl ; cout << x << " ▁ is ▁ " << Hex ( x ) << endl ; cout << y << " ▁ is ▁ " << Hex ( y ) << endl ; cout << z << " ▁ is ▁ " << Hex ( z ) << endl ; return 0 ; }
Find the player who will win the Coin game | C ++ program to find the player who wins the game ; Function to check the wining player ; As discussed in the above approach ; Driver function
#include <bits/stdc++.h> NEW_LINE using namespace std ; void findWinner ( int n ) { if ( ( n - 1 ) % 6 == 0 ) { cout << " Second ▁ Player ▁ wins ▁ the ▁ game " ; } else { cout << " First ▁ Player ▁ wins ▁ the ▁ game " ; } } int main ( ) { int n = 7 ; findWinner ( n ) ; }
Find ways to arrange K green balls among N balls such that exactly i moves is needed to collect all K green balls | C ++ implementation of the approach ; To store the factorial and the factorial mod inverse of a number ; Function to find ( a ^ m1 ) % mod ; Function to find factorial of all the numbers ; Function to find the factorial mod inverse of all the numbers ; Function to return nCr ; Function to find ways to arrange K green balls among N balls such that we need exactly i moves to collect all K green balls ; Driver code ; Function call
#include <bits/stdc++.h> NEW_LINE using namespace std ; #define N 100005 NEW_LINE #define mod (int)(1e9 + 7) NEW_LINE int factorial [ N ] , modinverse [ N ] ; int power ( int a , int m1 ) { if ( m1 == 0 ) return 1 ; else if ( m1 == 1 ) return a ; else if ( m1 == 2 ) return ( 1LL * a * a ) % mod ; else if ( m1 & 1 ) return ( 1LL * a * power ( power ( a , m1 / 2 ) , 2 ) ) % mod ; else return power ( power ( a , m1 / 2 ) , 2 ) % mod ; } void factorialfun ( ) { factorial [ 0 ] = 1 ; for ( int i = 1 ; i < N ; i ++ ) factorial [ i ] = ( 1LL * factorial [ i - 1 ] * i ) % mod ; } void modinversefun ( ) { modinverse [ N - 1 ] = power ( factorial [ N - 1 ] , mod - 2 ) % mod ; for ( int i = N - 2 ; i >= 0 ; i -- ) modinverse [ i ] = ( 1LL * modinverse [ i + 1 ] * ( i + 1 ) ) % mod ; } int binomial ( int n , int r ) { if ( r > n ) return 0 ; int a = ( 1LL * factorial [ n ] * modinverse [ n - r ] ) % mod ; a = ( 1LL * a * modinverse [ r ] ) % mod ; return a ; } void arrange_balls ( int n , int k ) { factorialfun ( ) ; modinversefun ( ) ; for ( int i = 1 ; i <= k ; i ++ ) cout << ( 1LL * binomial ( n - k + 1 , i ) * binomial ( k - 1 , i - 1 ) ) % mod << " ▁ " ; } int main ( ) { int n = 5 , k = 3 ; arrange_balls ( n , k ) ; return 0 ; }
Minimum inversions required so that no two adjacent elements are same | C ++ implementation of the approach ; Function to return the minimum inversions required so that no two adjacent elements are same ; To store the inversions required to make the array { 1 , 0 , 1 , 0 , 1 , 0 , 1 , ... } and { 0 , 1 , 0 , 1 , 0 , 1 , 0 , ... } respectively ; Find all the changes required ; Return the required answer ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int min_changes ( int a [ ] , int n ) { int ans_a = 0 , ans_b = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( i % 2 == 0 ) { if ( a [ i ] == 0 ) ans_a ++ ; else ans_b ++ ; } else { if ( a [ i ] == 0 ) ans_b ++ ; else ans_a ++ ; } } return min ( ans_a , ans_b ) ; } int main ( ) { int a [ ] = { 1 , 0 , 0 , 1 , 0 , 0 , 1 , 0 } ; int n = sizeof ( a ) / sizeof ( a [ 0 ] ) ; cout << min_changes ( a , n ) ; return 0 ; }
Sum of all the numbers present at given level in Modified Pascal ’ s triangle | C ++ program to calculate sum of all the numbers present at given level in an Modified Pascals triangle ; Function to calculate sum ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void ans ( int n ) { if ( n == 1 ) cout << "1" ; else cout << "0" ; } int main ( ) { int n = 2 ; ans ( n ) ; return 0 ; }
Find if there exists multiple ways to draw line through ( x , y ) to cut rectangle in equal halfs | C ++ implementation of the approach ; Function that returns true if multiple lines are possible passing through ( x , y ) that divide the given rectangle into two equal parts ; If the point ( x , y ) is the centre of the rectangle ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int isPossible ( int w , int h , int x , int y ) { if ( x * 2 == w && y * 2 == h ) return true ; return false ; } int main ( ) { int w = 1 , h = 2 , x = 1 , y = 2 ; if ( isPossible ( w , h , x , y ) ) cout << " Yes " ; else cout << " No " ; return 0 ; }
Minimize the number by changing at most K digits | C ++ implementation of the approach ; Function to return the minimized number ; Total digits in the number ; If the string is empty or there are no operations to perform ; "0" is a valid number ; If the first digit is not already 1 then update it to 1 and decrement k ; While there are operations left and the number can still be updated ; If the current digit is not already 0 then update it to 0 and decrement k ; Return the minimised number ; Driver code
#include <iostream> NEW_LINE using namespace std ; string minNum ( string num , int k ) { int len = num . length ( ) ; if ( len == 0 k == 0 ) return num ; if ( len == 1 ) return "0" ; if ( num [ 0 ] != '1' ) { num [ 0 ] = '1' ; k -- ; } int i = 1 ; while ( k > 0 && i < len ) { if ( num [ i ] != '0' ) { num [ i ] = '0' ; k -- ; } i ++ ; } return num ; } int main ( ) { string num = "91945" ; int k = 3 ; cout << minNum ( num , k ) ; return 0 ; }
Form N by adding 1 or 2 in minimum number of operations X where X is divisible by M | C ++ program to find minimum number of steps to cover distance x ; Function to calculate the minimum number of steps required total steps taken is divisible by m and only 1 or 2 steps can be taken at a time ; If m > n ans is - 1 ; else discussed above approach ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int minsteps ( int n , int m ) { if ( m > n ) { return -1 ; } else { return ( ( n + 1 ) / 2 + m - 1 ) / m * m ; } } int main ( ) { int n = 17 , m = 4 ; int ans = minsteps ( n , m ) ; cout << ans << ' ' ; return 0 ; }
Compare numbers represented by Linked Lists | C ++ implementation of the approach ; Structure for a linked list node ; A helper function to remove zeros from the start of the linked list ; A helper function to find the length of linked list ; Given a reference ( pointer to pointer ) to the head of a list and an int , push a new node on the front of the list . ; Allocate node ; Set the data ; Link the old list after the new node ; Set the head to point to the new node ; Function to compare the numbers represented as linked lists ; Remover leading zeroes from the linked lists ; Since the number represented by a has a greater length , it will be greater ; If the lengths of two numbers are equal we have to check their magnitudes ; If we reach here , then a and b are not NULL and their data is same , so move to next nodes in both lists ; If linked lists are identical , then we need to return zero ; Driver code ; The constructed linked lists are : a : 5 -> 6 -> 7 b : 2 -> 3 -> 3
#include <bits/stdc++.h> NEW_LINE using namespace std ; struct Node { int data ; struct Node * next ; } ; Node * removeLeadingZeros ( struct Node * a ) { if ( a != NULL && a -> data == 0 ) return removeLeadingZeros ( a -> next ) ; else return a ; } int getSize ( struct Node * a ) { int sz = 0 ; while ( a != NULL ) { a = a -> next ; sz ++ ; } return sz ; } void push ( struct Node * * head_ref , int new_data ) { struct Node * new_node = ( struct Node * ) malloc ( sizeof ( struct Node ) ) ; new_node -> data = new_data ; new_node -> next = ( * head_ref ) ; ( * head_ref ) = new_node ; } int compare ( struct Node * a , struct Node * b ) { a = removeLeadingZeros ( a ) ; b = removeLeadingZeros ( b ) ; int lenA = getSize ( a ) ; int lenB = getSize ( b ) ; if ( lenA > lenB ) { return 1 ; } else if ( lenB > lenA ) { return -1 ; } while ( a != NULL && b != NULL ) { if ( a -> data > b -> data ) return 1 ; else if ( a -> data < b -> data ) return -1 ; a = a -> next ; b = b -> next ; } return 0 ; } int main ( ) { struct Node * a = NULL ; push ( & a , 7 ) ; push ( & a , 6 ) ; push ( & a , 5 ) ; struct Node * b = NULL ; push ( & b , 3 ) ; push ( & b , 3 ) ; push ( & b , 2 ) ; cout << compare ( a , b ) ; return 0 ; }
Sum of the updated array after performing the given operation | C ++ implementation of the approach ; Utility function to return the sum of the array ; Function to return the sum of the modified array ; Find the sum of the subarray arr [ i + 1. . . n - 1 ] ; Subtract the subarray sum ; Return the sum of the modified array ; Driver code
#include <iostream> NEW_LINE using namespace std ; int sumArr ( int arr [ ] , int n ) { int sum = 0 ; for ( int i = 0 ; i < n ; i ++ ) sum += arr [ i ] ; return sum ; } int sumModArr ( int arr [ ] , int n ) { for ( int i = 0 ; i < n - 1 ; i ++ ) { int subSum = 0 ; for ( int j = i + 1 ; j < n ; j ++ ) { subSum += arr [ j ] ; } arr [ i ] -= subSum ; } return sumArr ( arr , n ) ; } int main ( ) { int arr [ ] = { 40 , 25 , 12 , 10 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << sumModArr ( arr , n ) ; return 0 ; }
Find the minimum possible health of the winning player | C ++ implementation of the approach ; Function to return the minimum possible health of the last player ; Find the GCD of the array elements ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int minHealth ( int health [ ] , int n ) { int gcd = 0 ; for ( int i = 0 ; i < n ; i ++ ) { gcd = __gcd ( gcd , health [ i ] ) ; } return gcd ; } int main ( ) { int health [ ] = { 5 , 6 , 1 , 2 , 3 , 4 } ; int n = sizeof ( health ) / sizeof ( int ) ; cout << minHealth ( health , n ) ; return 0 ; }
Construct an array from its pair | C ++ implementation of the approach ; Utility function to print the array ; Function to generate the original array from the pair - product array ; First element of the resulting array ; Find all the other elements ; Print the elements of the generated array ; Driver code
#include <iostream> NEW_LINE #include <math.h> NEW_LINE using namespace std ; void printArr ( int arr [ ] , int n ) { for ( int i = 0 ; i < n ; i ++ ) cout << arr [ i ] << " ▁ " ; } void constructArr ( int pair [ ] , int n ) { int size = ( 1 + ( int ) sqrt ( 1 + 8 * n ) ) / 2 ; int arr [ size ] ; arr [ 0 ] = sqrt ( ( pair [ 0 ] * pair [ 1 ] ) / pair [ size - 1 ] ) ; for ( int i = 1 ; i < size ; i ++ ) arr [ i ] = pair [ i - 1 ] / arr [ 0 ] ; printArr ( arr , size ) ; } int main ( ) { int pair [ ] = { 48 , 18 , 24 , 24 , 32 , 12 } ; int n = sizeof ( pair ) / sizeof ( int ) ; constructArr ( pair , n ) ; return 0 ; }
Count of odd and even sum pairs in an array | C ++ implementation of the approach ; Function to find the count of pairs with odd sum and the count of pairs with even sum ; To store the count of even and odd number from the array ; If the current element is even ; If it is odd ; To store the count of pairs with even sum ; All the even elements will make pairs with each other and the sum of the pair will be even ; All the odd elements will make pairs with each other and the sum of the pair will be even ; To store the count of pairs with odd sum ; All the even elements will make pairs with all the odd element and the sum of the pair will be odd ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void findPairs ( int arr [ ] , int n ) { int cntEven = 0 , cntOdd = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( arr [ i ] % 2 == 0 ) cntEven ++ ; else cntOdd ++ ; } int evenPairs = 0 ; evenPairs += ( ( cntEven * ( cntEven - 1 ) ) / 2 ) ; evenPairs += ( ( cntOdd * ( cntOdd - 1 ) ) / 2 ) ; int oddPairs = 0 ; oddPairs += ( cntEven * cntOdd ) ; cout << " Odd ▁ pairs ▁ = ▁ " << oddPairs << endl ; cout << " Even ▁ pairs ▁ = ▁ " << evenPairs ; } int main ( ) { int arr [ ] = { 1 , 2 , 3 , 4 , 5 } ; int n = sizeof ( arr ) / sizeof ( int ) ; findPairs ( arr , n ) ; return 0 ; }
Number of ways to distribute N Paper Set among M students | C ++ implementation of the approach ; Function to return n ! % 1000000007 ; To store the factorial ; Find the factorial ; Function to return the count of possible ways ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; const int MOD = 1000000007 ; int factMod ( int n ) { long fact = 1 ; for ( int i = 2 ; i <= n ; i ++ ) { fact *= ( i % MOD ) ; fact %= MOD ; } return fact ; } int countWays ( int n , int m ) { return factMod ( m ) ; } int main ( ) { int n = 2 , m = 2 ; cout << countWays ( n , m ) ; return 0 ; }
Program for nth Fuss – Catalan Number | C ++ program for nth FussCatalan Number ; Returns value of Binomial Coefficient C ( n , k ) ; Since C ( n , k ) = C ( n , n - k ) ; Calculate value of [ n * ( n - 1 ) * -- - * ( n - k + 1 ) ] / [ k * ( k - 1 ) * -- - * 1 ] ; A Binomial coefficient based function to find nth FussCatalan number in O ( n ) time ; Calculate value of 3 nCn ; return 3 nCn / ( 2 n + 1 ) ; Driver code
#include <iostream> NEW_LINE using namespace std ; unsigned long int binomialCoeff ( unsigned int n , unsigned int k ) { unsigned long int res = 1 ; if ( k > n - k ) k = n - k ; for ( int i = 0 ; i < k ; ++ i ) { res *= ( n - i ) ; res /= ( i + 1 ) ; } return res ; } unsigned long int Fuss_catalan ( unsigned int n ) { unsigned long int c = binomialCoeff ( 3 * n , n ) ; return c / ( 2 * n + 1 ) ; } int main ( ) { for ( int i = 0 ; i < 10 ; i ++ ) cout << Fuss_catalan ( i ) << " ▁ " ; return 0 ; }
Check if a number is Euler Pseudoprime | C ++ implementation of the approach ; Function that returns true if n is composite ; Check if there is any divisor of n . we only need check divisor till sqrt ( n ) because if there is divisor which is greater than sqrt ( n ) then there must be a divisor which is less than sqrt ( n ) ; Iterative Function to calculate ( x ^ y ) % p in O ( log y ) ; Initialize result ; Update x if it is greater than or equal to p ; If y is odd , multiply x with result ; y must be even now y = y >> 1 ; y = y / 2 ; Function that returns true if N is Euler Pseudoprime to the base A ; Invalid base ; N is not a composite odd number ; If A and N are not coprime ; All the conditions for Euler Pseudoprime are satisfied ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool isComposite ( int n ) { for ( int i = 2 ; i <= sqrt ( n ) ; i ++ ) { if ( n % i == 0 ) return true ; } return false ; } int Power ( int x , int y , int p ) { int res = 1 ; x = x % p ; while ( y > 0 ) { if ( y & 1 ) { res = ( res * x ) % p ; } x = ( x * x ) % p ; } return res ; } bool isEulerPseudoprime ( int N , int A ) { if ( A <= 0 ) return false ; if ( N % 2 == 0 || ! isComposite ( N ) ) return false ; if ( __gcd ( A , N ) != 1 ) return false ; int mod = Power ( A , ( N - 1 ) / 2 , N ) ; if ( mod != 1 && mod != N - 1 ) return false ; return true ; } int main ( ) { int N = 121 , A = 3 ; if ( isEulerPseudoprime ( N , A ) ) cout << " Yes " ; else cout << " No " ; return 0 ; }
Minimum difference between any two primes from the given range | C ++ implementation of the approach ; Function for Sieve of Eratosthenes ; Function to return the minimum difference between any two prime numbers from the given range [ L , R ] ; Find the first prime from the range ; Find the second prime from the range ; If the number of primes in the given range is < 2 ; To store the minimum difference between two consecutive primes from the range ; Range left to check for primes ; For every integer in the range ; If the current integer is prime ; If the difference between i and snd is minimum so far ; Driver code ; Generate primes
#include <bits/stdc++.h> NEW_LINE using namespace std ; const int sz = 1e5 ; bool isPrime [ sz + 1 ] ; void sieve ( ) { memset ( isPrime , true , sizeof ( isPrime ) ) ; isPrime [ 0 ] = isPrime [ 1 ] = false ; for ( int i = 2 ; i * i <= sz ; i ++ ) { if ( isPrime [ i ] ) { for ( int j = i * i ; j < sz ; j += i ) { isPrime [ j ] = false ; } } } } int minDifference ( int L , int R ) { int fst = 0 ; for ( int i = L ; i <= R ; i ++ ) { if ( isPrime [ i ] ) { fst = i ; break ; } } int snd = 0 ; for ( int i = fst + 1 ; i <= R ; i ++ ) { if ( isPrime [ i ] ) { snd = i ; break ; } } if ( snd == 0 ) return -1 ; int diff = snd - fst ; int left = snd + 1 ; int right = R ; for ( int i = left ; i <= right ; i ++ ) { if ( isPrime [ i ] ) { if ( i - snd <= diff ) { fst = snd ; snd = i ; diff = snd - fst ; } } } return diff ; } int main ( ) { sieve ( ) ; int L = 21 , R = 50 ; cout << minDifference ( L , R ) ; return 0 ; }
Number of non | C ++ implementation of the approach ; Function to return the required count ; To store the final result ; Two pointer loop ; Initialising j ; Looping till the subarray increases ; Update ret ; Update i ; Return ret ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int findCnt ( int * arr , int n , int k ) { int ret = 0 ; int i = 0 ; while ( i < n ) { int j = i + 1 ; while ( j < n and arr [ j ] > = arr [ j - 1 ] ) j ++ ; int x = max ( 0 , j - i - k + 1 ) ; ret += ( x * ( x + 1 ) ) / 2 ; i = j ; } return ret ; } int main ( ) { int arr [ ] = { 5 , 4 , 3 , 2 , 1 } ; int n = sizeof ( arr ) / sizeof ( int ) ; int k = 2 ; cout << findCnt ( arr , n , k ) ; return 0 ; }
Count of elements which are second smallest among three consecutive elements | C ++ implementation of the approach ; Function to return the count of elements P [ i ] such that P [ i ] is the second smallest among P [ i 1 ] , P [ i ] and P [ i + 1 ] ; To store the required answer ; Traverse from the second element to the second last element ; Return the required answer ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int countElements ( int p [ ] , int n ) { int ans = 0 ; for ( int i = 1 ; i < n - 1 ; i ++ ) { if ( p [ i - 1 ] > p [ i ] and p [ i ] > p [ i + 1 ] ) ans ++ ; else if ( p [ i - 1 ] < p [ i ] and p [ i ] < p [ i + 1 ] ) ans ++ ; } return ans ; } int main ( ) { int p [ ] = { 2 , 5 , 1 , 3 , 4 } ; int n = sizeof ( p ) / sizeof ( p [ 0 ] ) ; cout << countElements ( p , n ) ; return 0 ; }
Count integers in the range [ A , B ] that are not divisible by C and D | C ++ implementation of the approach ; Function to return the count of integers from the range [ a , b ] that are not divisible by c and d ; Numbers which are divisible by c ; Numbers which are divisible by d ; Find lowest common factor of c and d ; Numbers which are divisible by both c and d ; Return the required answer ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int countNums ( int a , int b , int c , int d ) { int x = b / c - ( a - 1 ) / c ; int y = b / d - ( a - 1 ) / d ; int k = ( c * d ) / __gcd ( c , d ) ; int z = b / k - ( a - 1 ) / k ; return b - a + 1 - x - y + z ; } int main ( ) { int a = 10 , b = 50 , c = 4 , d = 6 ; cout << countNums ( a , b , c , d ) ; return 0 ; }
Number of non | C ++ implementation of the approach ; Function to return the count of increasing subarrays of length k ; To store the final result ; Two pointer loop ; Initialising j ; Looping till the subarray increases ; Updating the required count ; Updating i ; Returning res ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int cntSubArrays ( int * arr , int n , int k ) { int res = 0 ; int i = 0 ; while ( i < n ) { int j = i + 1 ; while ( j < n and arr [ j ] > = arr [ j - 1 ] ) j ++ ; res += max ( j - i - k + 1 , 0 ) ; i = j ; } return res ; } int main ( ) { int arr [ ] = { 1 , 2 , 3 , 2 , 5 } ; int n = sizeof ( arr ) / sizeof ( int ) ; int k = 2 ; cout << cntSubArrays ( arr , n , k ) ; return 0 ; }
Longest sub | C ++ implementation of the approach ; Function to return the length of the largest subsequence with minimum possible LCM ; Minimum value from the array ; To store the frequency of the minimum element in the array ; If current element is equal to the minimum element ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int maxLen ( int * arr , int n ) { int min_val = * min_element ( arr , arr + n ) ; int freq = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( arr [ i ] == min_val ) freq ++ ; } return freq ; } int main ( ) { int arr [ ] = { 1 , 3 , 1 } ; int n = sizeof ( arr ) / sizeof ( int ) ; cout << maxLen ( arr , n ) ; return 0 ; }
Program to find the last digit of X in base Y | C ++ Program to find the last digit of X in base Y ; Function to find the last digit of X in base Y ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void last_digit ( int X , int Y ) { cout << X % Y ; } int main ( ) { int X = 55 , Y = 3 ; last_digit ( X , Y ) ; return 0 ; }
Count of squares that can be drawn without lifting the pencil | C ++ implementation of the approach ; Function to return the count of squares that can be formed ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int countSquares ( int n ) { return ( pow ( n , 2 ) - ( 2 * n ) + 2 ) ; } int main ( ) { int n = 2 ; cout << countSquares ( n ) ; return 0 ; }
Integer part of the geometric mean of the divisors of N | C ++ implementation of the approach ; Function to return the integer part of the geometric mean of the divisors of n ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int geometricMean ( int n ) { return sqrt ( n ) ; } int main ( ) { int n = 16 ; cout << geometricMean ( n ) ; return 0 ; }
Number of K 's such that the given array can be divided into two sets satisfying the given conditions | C ++ implementation of the approach ; Function to return the count of K 's such that the array can be divided into two sets containing equal number of elements when all the elements less than K are in one set and the rest of the elements are in the other set ; Sort the given array ; Return number of such Ks ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int two_sets ( int a [ ] , int n ) { sort ( a , a + n ) ; return a [ n / 2 ] - a [ ( n / 2 ) - 1 ] ; } int main ( ) { int a [ ] = { 1 , 4 , 4 , 6 , 7 , 9 } ; int n = sizeof ( a ) / sizeof ( a [ 0 ] ) ; cout << two_sets ( a , n ) ; return 0 ; }
Count of pairs in an array such that the highest power of 2 that divides their product is 1 | C ++ implementation of the approach ; Function to return the count of valid pairs ; To store the count of odd numbers and the count of even numbers such that 2 is the only even factor of that number ; If current number is odd ; If current number is even and 2 is the only even factor of it ; Calculate total number of valid pairs ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int cntPairs ( int a [ ] , int n ) { int odd = 0 , even = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( a [ i ] % 2 == 1 ) odd ++ ; else if ( ( a [ i ] / 2 ) % 2 == 1 ) even ++ ; } int ans = odd * even + ( odd * ( odd - 1 ) ) / 2 ; return ans ; } int main ( ) { int a [ ] = { 4 , 2 , 7 , 11 , 14 , 15 , 18 } ; int n = sizeof ( a ) / sizeof ( a [ 0 ] ) ; cout << cntPairs ( a , n ) ; return 0 ; }
Make the array non | C ++ implementation of the approach ; Function to make array non - decreasing ; Take the first element ; Perform the operation ; Traverse the array ; Next element ; If next element is greater than the current element then decrease it to increase the possibilities ; It is not possible to make the array non - decreasing with the given operation ; Next element is now the current ; The array can be made non - decreasing with the given operation ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool isPossible ( int a [ ] , int n ) { int cur = a [ 0 ] ; cur -- ; for ( int i = 1 ; i < n ; i ++ ) { int nxt = a [ i ] ; if ( nxt > cur ) nxt -- ; else if ( nxt < cur ) return false ; cur = nxt ; } return true ; } int main ( ) { int a [ ] = { 1 , 2 , 1 , 2 , 3 } ; int n = sizeof ( a ) / sizeof ( a [ 0 ] ) ; if ( isPossible ( a , n ) ) cout << " Yes " ; else cout << " No " ; return 0 ; }
Find the maximum element in the array other than Ai | C ++ implementation of the approach ; Function to find maximum element among ( N - 1 ) elements other than a [ i ] for each i from 1 to N ; To store prefix max element ; To store suffix max element ; Find the maximum element in the array other than a [ i ] ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int max_element ( int a [ ] , int n ) { int pre [ n ] ; pre [ 0 ] = a [ 0 ] ; for ( int i = 1 ; i < n ; i ++ ) pre [ i ] = max ( pre [ i - 1 ] , a [ i ] ) ; int suf [ n ] ; suf [ n - 1 ] = a [ n - 1 ] ; for ( int i = n - 2 ; i >= 0 ; i -- ) suf [ i ] = max ( suf [ i + 1 ] , a [ i ] ) ; for ( int i = 0 ; i < n ; i ++ ) { if ( i == 0 ) cout << suf [ i + 1 ] << " ▁ " ; else if ( i == n - 1 ) cout << pre [ i - 1 ] << " ▁ " ; else cout << max ( pre [ i - 1 ] , suf [ i + 1 ] ) << " ▁ " ; } } int main ( ) { int a [ ] = { 2 , 5 , 6 , 1 , 3 } ; int n = sizeof ( a ) / sizeof ( a [ 0 ] ) ; max_element ( a , n ) ; return 0 ; }
Find the Kth position element of the given sequence | C ++ implementation of the approach ; Function to return the kth number from the required sequence ; Count of odd integers in the sequence ; kth number is even ; It is odd ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int kthNum ( int n , int k ) { int a = ( n + 1 ) / 2 ; if ( k > a ) return ( 2 * ( k - a ) ) ; return ( 2 * k - 1 ) ; } int main ( ) { int n = 7 , k = 7 ; cout << kthNum ( n , k ) ; return 0 ; }
Find K such that | A | C ++ implementation of the approach ; Function to find k such that | a - k | = | b - k | ; If ( a + b ) is even ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int find_k ( int a , int b ) { if ( ( a + b ) % 2 == 0 ) return ( ( a + b ) / 2 ) ; return -1 ; } int main ( ) { int a = 2 , b = 16 ; cout << find_k ( a , b ) ; return 0 ; }
Increasing permutation of first N natural numbers | C ++ implementation of the approach ; Function that returns true if it is possible to make the permutation increasing by swapping any two numbers ; To count misplaced elements ; Count all misplaced elements ; If possible ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool isPossible ( int a [ ] , int n ) { int k = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( a [ i ] != i + 1 ) k ++ ; } if ( k <= 2 ) return true ; return false ; } int main ( ) { int a [ ] = { 5 , 2 , 3 , 4 , 1 } ; int n = sizeof ( a ) / sizeof ( a [ 0 ] ) ; if ( isPossible ( a , n ) ) cout << " Yes " ; else cout << " No " ; return 0 ; }
Find the number of positive integers less than or equal to N that have an odd number of digits | C ++ implementation of the approach ; Function to return the number of positive integers less than or equal to N that have odd number of digits ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int odd_digits ( int n ) { if ( n < 10 ) return n ; else if ( n / 10 < 10 ) return 9 ; else if ( n / 100 < 10 ) return 9 + n - 99 ; else if ( n / 1000 < 10 ) return 9 + 900 ; else if ( n / 10000 < 10 ) return 909 + n - 9999 ; else return 90909 ; } int main ( ) { int n = 893 ; cout << odd_digits ( n ) ; return 0 ; }
Count of N | C ++ implementation of the approach ; Function to return the count of N - digit palindrome numbers ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int nDigitPalindromes ( int n ) { return ( 9 * pow ( 10 , ( n - 1 ) / 2 ) ) ; } int main ( ) { int n = 2 ; cout << nDigitPalindromes ( n ) ; return 0 ; }
Maximum LCM among all pairs ( i , j ) of first N natural numbers | C ++ implementation of the approach ; Function to return the maximum LCM among all the pairs ( i , j ) of first n natural numbers ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int maxLCM ( int n ) { return ( n * ( n - 1 ) ) ; } int main ( ) { int n = 3 ; cout << maxLCM ( n ) ; return 0 ; }
Sum of all the numbers in the Nth row of the given triangle | C ++ implementation of the approach ; Function to return the sum of the nth row elements of the given triangle ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int getSum ( int n ) { return ( ( n - 1 ) + pow ( n , 2 ) ) ; } int main ( ) { int n = 3 ; cout << getSum ( n ) ; return 0 ; }
Number of edges in a perfect binary tree with N levels | C ++ implementation of the approach ; Function to return the count of edges in an n - level perfect binary tree ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int cntEdges ( int n ) { int edges = pow ( 2 , n ) - 2 ; return edges ; } int main ( ) { int n = 4 ; cout << cntEdges ( n ) ; return 0 ; }
Number of cells in the Nth order figure | C ++ implementation of the approach ; Function to return the number of cells in the nth order figure of the given type ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int cntCells ( int n ) { int cells = pow ( n , 2 ) + pow ( n - 1 , 2 ) ; return cells ; } int main ( ) { int n = 3 ; cout << cntCells ( n ) ; return 0 ; }
Sum of all the numbers in the Nth parenthesis | C ++ implementation of the approach ; Function to return the sum of the numbers in the nth parenthesis ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int findSum ( int n ) { return pow ( n , 3 ) ; } int main ( ) { int n = 3 ; cout << findSum ( n ) ; return 0 ; }
Find the count of natural Hexadecimal numbers of size N | C ++ implementation of the above approach ; Function to return the count of n - digit natural hexadecimal numbers ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int count ( int n ) { return 15 * pow ( 16 , n - 1 ) ; } int main ( ) { int n = 2 ; cout << count ( n ) ; return 0 ; }
Largest Even and Odd N | C ++ implementation of the approach ; Function to print the largest n - digit even and odd numbers in octal number system ; Append '7' ( N - 1 ) times ; Append '6' for an even number ; Append '7' for an odd number ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void findNumbers ( int n ) { string ans = string ( n - 1 , '7' ) ; string even = ans + '6' ; string odd = ans + '7' ; cout << " Even ▁ : ▁ " << even << endl ; cout << " Odd ▁ : ▁ " << odd << endl ; } int main ( ) { int n = 4 ; findNumbers ( n ) ; return 0 ; }
Nth term of a Custom Fibonacci series | C ++ implementation of the Custom Fibonacci series ; Function to return the nth term of the required sequence ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int nth_term ( int a , int b , int n ) { int z = 0 ; if ( n % 6 == 1 ) z = a ; else if ( n % 6 == 2 ) z = b ; else if ( n % 6 == 3 ) z = b - a ; else if ( n % 6 == 4 ) z = - a ; else if ( n % 6 == 5 ) z = - b ; if ( n % 6 == 0 ) z = - ( b - a ) ; return z ; } int main ( ) { int a = 10 , b = 17 , n = 3 ; cout << nth_term ( a , b , n ) ; return 0 ; }
Check whether the given integers a , b , c and d are in proportion | C ++ implementation of the approach ; Function that returns true if the given four integers are in proportion ; Array will consist of only four integers ; Sort the array ; Find the product of extremes and means ; If the products are equal ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool inProportion ( int arr [ ] ) { int n = 4 ; sort ( arr , arr + n ) ; long extremes = ( long ) arr [ 0 ] * ( long ) arr [ 3 ] ; long means = ( long ) arr [ 1 ] * ( long ) arr [ 2 ] ; if ( extremes == means ) return true ; return false ; } int main ( ) { int arr [ ] = { 1 , 2 , 4 , 2 } ; if ( inProportion ( arr ) ) cout << " Yes " ; else cout << " No " ; return 0 ; }
Find the deleted value from the array when average of original elements is given | C ++ implementation of the approach ; Function to return the missing element ; Find the sum of the array elements ; The numerator and the denominator of the equation ; If not divisible then X is not an integer it is a floating point number ; Return X ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int findMissing ( int arr [ ] , int n , int k , int avg ) { int sum = 0 ; for ( int i = 0 ; i < n ; i ++ ) { sum += arr [ i ] ; } int num = ( avg * ( n + k ) ) - sum ; int den = k ; if ( num % den != 0 ) return -1 ; return ( num / den ) ; } int main ( ) { int k = 3 , avg = 4 ; int arr [ ] = { 2 , 7 , 3 } ; int n = sizeof ( arr ) / sizeof ( int ) ; cout << findMissing ( arr , n , k , avg ) ; return 0 ; }
Count of N | C ++ implementation of the approach ; Function to return the factorial of n ; Function to return the count of n - digit numbers with all distinct digits ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int factorial ( int n ) { if ( n == 0 ) return 1 ; return n * factorial ( n - 1 ) ; } int countNum ( int n ) { if ( n > 10 ) return 0 ; return ( 9 * factorial ( 9 ) / factorial ( 10 - n ) ) ; } int main ( ) { int n = 3 ; cout << countNum ( n ) ; return 0 ; }
Maximum number of distinct positive integers that can be used to represent N | C ++ implementation of the approach ; Function to return the required count ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int count ( int n ) { return int ( ( -1 + sqrt ( 1 + 8 * n ) ) / 2 ) ; } int main ( ) { int n = 10 ; cout << count ( n ) ; return 0 ; }
Find the previous fibonacci number | C ++ implementation of the approach ; Function to return the previous fibonacci number ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int previousFibonacci ( int n ) { double a = n / ( ( 1 + sqrt ( 5 ) ) / 2.0 ) ; return round ( a ) ; } int main ( ) { int n = 8 ; cout << ( previousFibonacci ( n ) ) ; }
Find the quadratic equation from the given roots | C ++ implementation of the approach ; Function to find the quadratic equation whose roots are a and b ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void findEquation ( int a , int b ) { int sum = ( a + b ) ; int product = ( a * b ) ; cout << " x ^ 2 ▁ - ▁ ( " << sum << " x ) ▁ + ▁ ( " << product << " ) ▁ = ▁ 0" ; } int main ( ) { int a = 2 , b = 3 ; findEquation ( a , b ) ; return 0 ; }
Smallest N digit number which is a perfect fourth power | C ++ implementation of the approach ; Function to return the smallest n - digit number which is a perfect fourth power ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int cal ( int n ) { double res = pow ( ceil ( ( pow ( pow ( 10 , ( n - 1 ) ) , 1 / 4 ) ) ) , 4 ) ; return ( int ) res ; } int main ( ) { int n = 1 ; cout << ( cal ( n ) ) ; }
Count of 0 s in an N | C ++ implementation of the approach ; Function to return the count of 0 s in an n - level hexagon ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int count ( int n ) { return 3 * n * ( n - 1 ) + 1 ; } int main ( ) { int n = 3 ; cout << count ( n ) ; return 0 ; }
Number of words that can be made using exactly P consonants and Q vowels from the given string | C ++ implementation of the approach ; Function to return the value of nCk ; Function to return the factorial of n ; Function that returns true if ch is a vowel ; Function to return the number of words possible ; To store the count of vowels and consonanats in the given string ; If current character is a vowel ; Find the total possible words ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; #define lli long long int NEW_LINE lli binomialCoeff ( lli n , lli k ) { if ( k == 0 k == n ) return 1 ; return binomialCoeff ( n - 1 , k - 1 ) + binomialCoeff ( n - 1 , k ) ; } lli fact ( lli n ) { if ( n >= 1 ) return n * fact ( n - 1 ) ; else return 1 ; } bool isVowel ( char ch ) { if ( ch == ' a ' ch == ' e ' ch == ' i ' ch == ' o ' ch == ' u ' ) { return true ; } return false ; } lli countWords ( string s , int p , int q ) { lli countc = 0 , countv = 0 ; for ( int i = 0 ; i < s . length ( ) ; i ++ ) { if ( isVowel ( s [ i ] ) ) countv ++ ; else countc ++ ; } lli a = binomialCoeff ( countc , p ) ; lli b = binomialCoeff ( countv , q ) ; lli c = fact ( p + q ) ; lli ans = ( a * b ) * c ; return ans ; } int main ( ) { string s = " crackathon " ; int p = 4 , q = 3 ; cout << countWords ( s , p , q ) ; return 0 ; }
Count of elements on the left which are divisible by current element | C ++ implementation of the approach ; Utility function to print the elements of the array ; Function to generate and print the required array ; For every element of the array ; To store the count of elements on the left that the current element divides ; Print the generated array ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void printArr ( int arr [ ] , int n ) { for ( int i = 0 ; i < n ; i ++ ) cout << arr [ i ] << " ▁ " ; } void generateArr ( int A [ ] , int n ) { int B [ n ] ; for ( int i = 0 ; i < n ; i ++ ) { int cnt = 0 ; for ( int j = 0 ; j < i ; j ++ ) { if ( A [ j ] % A [ i ] == 0 ) cnt ++ ; } B [ i ] = cnt ; } printArr ( B , n ) ; } int main ( ) { int A [ ] = { 3 , 5 , 1 } ; int n = sizeof ( A ) / sizeof ( A [ 0 ] ) ; generateArr ( A , n ) ; return 0 ; }
Represent the given number as the sum of two composite numbers | C ++ implementation of the approach ; Function to find two composite numbers which when added give sum as n ; Only 8 and 10 can be represented as the sum of two composite integers ; If n is even ; If n is odd ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void findNums ( int n ) { if ( n <= 11 ) { if ( n == 8 ) cout << "4 ▁ 4" ; if ( n == 10 ) cout << "4 ▁ 6" ; else cout << " - 1" ; return ; } if ( n % 2 == 0 ) cout << "4 ▁ " << ( n - 4 ) ; else cout << "9 ▁ " << ( n - 9 ) ; } int main ( ) { int n = 13 ; findNums ( n ) ; return 0 ; }
Count of N | C ++ implementation of the approach ; Function to return the count of possible numbers ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int count ( int n ) { return pow ( 2 , n - 1 ) ; } int main ( ) { int n = 4 ; cout << count ( n ) ; return 0 ; }
Find the next fibonacci number | C ++ implementation of the approach ; Function to return the next fibonacci number ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int nextFibonacci ( int n ) { double a = n * ( 1 + sqrt ( 5 ) ) / 2.0 ; return round ( a ) ; } int main ( ) { int n = 5 ; cout << nextFibonacci ( n ) ; }
Sum of all the numbers present at given level in Pascal 's triangle | C ++ implementation of the above approach ; Function to find sum of numbers at Lth level in Pascals Triangle ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int sum ( int h ) { return pow ( 2 , h - 1 ) ; } int main ( ) { int L = 3 ; cout << sum ( L ) ; return 0 ; }
Product of values of all possible non | C ++ implementation of the approach ; Function to find product of all elements in all subsets ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int product ( int a [ ] , int n ) { int ans = 1 ; int val = pow ( 2 , n - 1 ) ; for ( int i = 0 ; i < n ; i ++ ) { ans *= pow ( a [ i ] , val ) ; } return ans ; } int main ( ) { int n = 2 ; int a [ ] = { 3 , 7 } ; cout << product ( a , n ) ; return 0 ; }
Program to find Nth odd Fibonacci Number | C ++ program for Nth odd fibonacci number ; Function to find nth odd fibonacci number ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int oddFib ( int n ) { n = ( 3 * n + 1 ) / 2 ; int a = -1 , b = 1 , c , i ; for ( i = 1 ; i <= n ; i ++ ) { c = a + b ; a = b ; b = c ; } return c ; } int main ( ) { int n = 4 ; cout << oddFib ( n ) ; return 0 ; }
Find a pair ( n , r ) in an integer array such that value of nPr is maximum | C ++ implementation of the approach ; Function to print the pair ( n , r ) such that nPr is maximum possible ; There should be atleast 2 elements ; Findex the largest 2 elements ; Driver code
#include <iostream> NEW_LINE using namespace std ; void findPair ( int arr [ ] , int n ) { if ( n < 2 ) { cout << " - 1" ; return ; } int i , first , second ; first = second = -1 ; for ( i = 0 ; i < n ; i ++ ) { if ( arr [ i ] > first ) { second = first ; first = arr [ i ] ; } else if ( arr [ i ] > second ) { second = arr [ i ] ; } } cout << " n ▁ = ▁ " << first << " ▁ and ▁ r ▁ = ▁ " << second ; } int main ( ) { int arr [ ] = { 0 , 2 , 3 , 4 , 1 , 6 , 8 , 9 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; findPair ( arr , n ) ; return 0 ; }
Sum of values of all possible non | C ++ implementation of the approach ; Function to return the required sum ; Find the sum of the array elements ; Every element appears 2 ^ ( n - 1 ) times ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int sum ( int arr [ ] , int n ) { int sum = 0 ; for ( int i = 0 ; i < n ; i ++ ) { sum += arr [ i ] ; } sum = sum * pow ( 2 , n - 1 ) ; return sum ; } int main ( ) { int arr [ ] = { 2 , 1 , 5 , 6 } ; int n = sizeof ( arr ) / sizeof ( int ) ; cout << sum ( arr , n ) ; return 0 ; }
Printing the Triangle Pattern using last term N | C ++ code for printing the Triangle Pattern using last term N ; Function to demonstrate printing pattern ; number of spaces ; character to be printed ; outer loop to handle number of rows n in this case ; inner loop to handle number spaces values changing acc . to requirement ; decrementing k after each loop ; inner loop to handle number of columns values changing acc . to outer loop ; printing stars ; ending line after each row ; Function to find the max height or the number of lines in the triangle pattern ; Driver Function
#include <bits/stdc++.h> NEW_LINE using namespace std ; void triangle ( int n ) { int k = 2 * n - 2 ; int ch = 1 ; for ( int i = 0 ; i < n ; i ++ ) { for ( int j = 0 ; j < k ; j ++ ) cout << " ▁ " ; k = k - 1 ; for ( int j = 0 ; j <= i ; j ++ ) { cout << ch ++ << " ▁ " ; } cout << endl ; } } int maxHeight ( int n ) { return ( ( ( int ) sqrt ( 1 + 8.0 * n ) ) - 1 ) / 2 ; } int main ( ) { int N = 9 ; triangle ( maxHeight ( N ) ) ; return 0 ; }
Number of ways in which N can be represented as the sum of two positive integers | C ++ implementation of the approach ; Function to return the number of distinct ways to represent n as the sum of two integers ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int ways ( int n ) { return n / 2 ; } int main ( ) { int n = 2 ; cout << ways ( n ) ; return 0 ; }
Number of ways to erase exactly one element in the Binary Array to make XOR zero | C ++ program to find the number of ways to erase exactly one element from this array to make XOR zero ; Function to find the number of ways ; Calculate the number of 1 ' s ▁ and ▁ 0' s ; Considering the 4 cases ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int no_of_ways ( int a [ ] , int n ) { int count_0 = 0 , count_1 = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( a [ i ] == 0 ) count_0 ++ ; else count_1 ++ ; } if ( count_1 % 2 == 0 ) return count_0 ; else return count_1 ; } int main ( ) { int n = 4 ; int a1 [ 4 ] = { 1 , 1 , 0 , 0 } ; cout << no_of_ways ( a1 , n ) << endl ; n = 5 ; int a2 [ 5 ] = { 1 , 1 , 1 , 0 , 0 } ; cout << no_of_ways ( a2 , n ) << endl ; n = 5 ; int a3 [ 5 ] = { 1 , 1 , 0 , 0 , 0 } ; cout << no_of_ways ( a3 , n ) << endl ; n = 6 ; int a4 [ 6 ] = { 1 , 1 , 1 , 0 , 0 , 0 } ; cout << no_of_ways ( a4 , n ) << endl ; return 0 ; }