text
stringlengths
17
4.49k
code
stringlengths
49
5.46k
Find count of numbers from 0 to n which satisfies the given equation for a value K | C ++ implementation to Find the total count of all the numbers from 0 to n which satisfies the given equation for a value K ; Function to find the values ; Calculate the LCM ; Calculate the multiples of lcm ; Find the values which satisfies the given condition ; Subtract the extra values ; Return the final result ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int findAns ( int a , int b , int n ) { int lcm = ( a * b ) / __gcd ( a , b ) ; int multiples = ( n / lcm ) + 1 ; int answer = max ( a , b ) * multiples ; int lastvalue = lcm * ( n / lcm ) + max ( a , b ) ; if ( lastvalue > n ) answer = answer - ( lastvalue - n - 1 ) ; return answer ; } int main ( ) { int a = 1 , b = 13 , n = 500 ; cout << findAns ( a , b , n ) << endl ; }
Program to find if two numbers and their AM and HM are present in an array using STL | C ++ program to check if two numbers are present in an array then their AM and HM are also present . Finally , find the GM of the numbers ; Function to find the Arithmetic Mean of 2 numbers ; Function to find the Harmonic Mean of 2 numbers ; Following function checks and computes the desired results based on the means ; Calculate means ; Hash container ( Set ) to store elements ; Insertion of array elements in the Set ; Conditionals to check if numbers are present in array by Hashing ; Conditionals to check if the AM and HM of the numbers are present in array ; If all conditions are satisfied , the Geometric Mean is calculated ; If numbers are found but the respective AM and HM are not found in the array ; If none of the conditions are satisfied ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; float ArithmeticMean ( float A , float B ) { return ( A + B ) / 2 ; } float HarmonicMean ( float A , float B ) { return ( 2 * A * B ) / ( A + B ) ; } void CheckArithmeticHarmonic ( float arr [ ] , float A , float B , int N ) { float AM = ArithmeticMean ( A , B ) ; float HM = HarmonicMean ( A , B ) ; unordered_set < float > Hash ; for ( int i = 0 ; i < N ; i ++ ) { Hash . insert ( arr [ i ] ) ; } if ( Hash . find ( A ) != Hash . end ( ) && Hash . find ( B ) != Hash . end ( ) ) { if ( Hash . find ( AM ) != Hash . end ( ) && Hash . find ( HM ) != Hash . end ( ) ) { cout << " GM ▁ = ▁ " ; printf ( " % 0.2f " , sqrt ( AM * HM ) ) ; } else { cout << " AM ▁ and ▁ HM ▁ not ▁ found " ; } } else { cout << " Numbers ▁ not ▁ found " ; } } int main ( ) { float arr [ ] = { 1.0 , 2.0 , 2.5 , 3.0 , 4.0 , 4.5 , 5.0 , 6.0 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; float A = 3.0 ; float B = 6.0 ; CheckArithmeticHarmonic ( arr , A , B , N ) ; return 0 ; }
Minimum decrements to make integer A divisible by integer B | C ++ implementation to count Total numbers moves to make integer A divisible by integer B ; Function that print number of moves required ; calculate modulo ; print the required answer ; Driver Code ; initialise A and B
#include <bits/stdc++.h> NEW_LINE using namespace std ; void movesRequired ( int a , int b ) { int total_moves = a % b ; cout << total_moves << " STRNEWLINE " ; } int main ( ) { int A = 10 , B = 3 ; movesRequired ( A , B ) ; return 0 ; }
Pythagorean Triplet with given sum using single loop | C ++ program to find the Pythagorean Triplet with given sum ; Function to calculate the Pythagorean triplet in O ( n ) ; Iterate a from 1 to N - 1. ; Calculate value of b ; The value of c = n - a - b ; Driver Code ; Function call
#include <bits/stdc++.h> NEW_LINE using namespace std ; void PythagoreanTriplet ( int n ) { int flag = 0 ; for ( int a = 1 ; a < n ; a ++ ) { int b = ( n * n - 2 * n * a ) / ( 2 * n - 2 * a ) ; int c = n - a - b ; if ( a * a + b * b == c * c && b > 0 && c > 0 ) { cout << a << " ▁ " << b << " ▁ " << c ; flag = 1 ; break ; } } if ( flag == 0 ) { cout << " - 1" ; } return ; } int main ( ) { int N = 12 ; PythagoreanTriplet ( N ) ; return 0 ; }
Check if there exists a number with X factors out of which exactly K are prime | C ++ program to check if there exists a number with X factors out of which exactly K are prime ; Function to check if such number exists ; To store the sum of powers of prime factors of X which determines the maximum count of numbers whose product can form X ; Determining the prime factors of X ; To check if the number is prime ; If X is 1 , then we cannot form a number with 1 factor and K prime factor ( as K is atleast 1 ) ; If X itself is prime then it can be represented as a power of only 1 prime factor which is X itself so we return true ; If sum of the powers of prime factors of X is greater than or equal to K , which means X can be represented as a product of K numbers , we return true ; In any other case , we return false as we cannot form a number with X factors and K prime factors ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool check ( int X , int K ) { int prime , temp , sqr , i ; prime = 0 ; temp = X ; sqr = sqrt ( X ) ; for ( i = 2 ; i <= sqr ; i ++ ) { while ( temp % i == 0 ) { temp = temp / i ; prime ++ ; } } if ( temp > 2 ) prime ++ ; if ( X == 1 ) return false ; if ( prime == 1 && K == 1 ) return true ; else if ( prime >= K ) return true ; else return false ; } int main ( ) { int X , K ; X = 4 ; K = 2 ; if ( check ( X , K ) ) cout << " Yes " ; else cout << " No " ; }
Print all Coprime path of a Binary Tree | C ++ program for printing Co - prime paths of binary Tree ; A Tree node ; Utility function to create a new node ; Vector to store all the prime numbers ; Function to store all the prime numbers in an array ; Create a boolean array " prime [ 0 . . N ] " and initialize all the entries in it as true . A value in prime [ i ] will finally be false if i is Not a prime , else true . ; If prime [ p ] is not changed , then it is a prime ; Update all multiples of p greater than or equal to the square of it numbers which are multiples of p and are less than p ^ 2 are already marked . ; Function to check whether Path is Co - prime or not ; Iterating through the array to find the maximum element in the array ; Incrementing the variable if any of the value has a factor ; If not co - prime ; Function to print a Co - Prime path ; Function to find co - prime paths of binary tree ; Base case ; Store the value in path vector ; Recursively call for left sub tree ; Recursively call for right sub tree ; Condition to check , if leaf node ; Condition to check , if path co - prime or not ; Print co - prime path ; Remove the last element from the path vector ; Function to find Co - Prime paths In a given binary tree ; To save all prime numbers ; Function call ; Driver Code ; Create Binary Tree as shown ; Print Co - Prime Paths
#include <bits/stdc++.h> NEW_LINE using namespace std ; struct Node { int key ; struct Node * left , * right ; } ; Node * newNode ( int key ) { Node * temp = new Node ; temp -> key = key ; temp -> left = temp -> right = NULL ; return ( temp ) ; } int N = 1000000 ; vector < int > prime ; void SieveOfEratosthenes ( ) { bool check [ N + 1 ] ; memset ( check , true , sizeof ( check ) ) ; for ( int p = 2 ; p * p <= N ; p ++ ) { if ( check [ p ] == true ) { prime . push_back ( p ) ; for ( int i = p * p ; i <= N ; i += p ) check [ i ] = false ; } } } bool isPathCo_Prime ( vector < int > & path ) { int max = 0 ; for ( auto x : path ) { if ( max < x ) max = x ; } for ( int i = 0 ; i * prime [ i ] <= max / 2 ; i ++ ) { int ct = 0 ; for ( auto x : path ) { if ( x % prime [ i ] == 0 ) ct ++ ; } if ( ct > 1 ) { return false ; } } return true ; } void printCo_PrimePaths ( vector < int > & path ) { for ( auto x : path ) { cout << x << " ▁ " ; } cout << endl ; } void findCo_PrimePaths ( struct Node * root , vector < int > & path ) { if ( root == NULL ) return ; path . push_back ( root -> key ) ; findCo_PrimePaths ( root -> left , path ) ; findCo_PrimePaths ( root -> right , path ) ; if ( root -> left == NULL && root -> right == NULL ) { if ( isPathCo_Prime ( path ) ) { printCo_PrimePaths ( path ) ; } } path . pop_back ( ) ; } void printCo_PrimePaths ( struct Node * node ) { SieveOfEratosthenes ( ) ; vector < int > path ; findCo_PrimePaths ( node , path ) ; } int main ( ) { Node * root = newNode ( 10 ) ; root -> left = newNode ( 48 ) ; root -> right = newNode ( 3 ) ; root -> right -> left = newNode ( 11 ) ; root -> right -> right = newNode ( 37 ) ; root -> right -> left -> left = newNode ( 7 ) ; root -> right -> left -> right = newNode ( 29 ) ; root -> right -> right -> left = newNode ( 42 ) ; root -> right -> right -> right = newNode ( 19 ) ; root -> right -> right -> right -> left = newNode ( 7 ) ; printCo_PrimePaths ( root ) ; return 0 ; }
Number of subsets with same AND , OR and XOR values in an Array | C ++ implementation to find the number of subsets with equal bitwise AND , OR and XOR values ; Function to find the number of subsets with equal bitwise AND , OR and XOR values ; Traverse through all the subsets ; Finding the subsets with the bits of ' i ' which are set ; Computing the bitwise AND ; Computing the bitwise OR ; Computing the bitwise XOR ; Comparing all the three values ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; const int mod = 1000000007 ; int countSubsets ( int a [ ] , int n ) { int answer = 0 ; for ( int i = 0 ; i < ( 1 << n ) ; i ++ ) { int bitwiseAND = -1 ; int bitwiseOR = 0 ; int bitwiseXOR = 0 ; for ( int j = 0 ; j < n ; j ++ ) { if ( i & ( 1 << j ) ) { if ( bitwiseAND == -1 ) bitwiseAND = a [ j ] ; else bitwiseAND &= a [ j ] ; bitwiseOR |= a [ j ] ; bitwiseXOR ^= a [ j ] ; } } if ( bitwiseAND == bitwiseOR && bitwiseOR == bitwiseXOR ) answer = ( answer + 1 ) % mod ; } return answer ; } int main ( ) { int N = 6 ; int A [ N ] = { 1 , 3 , 2 , 1 , 2 , 1 } ; cout << countSubsets ( A , N ) ; return 0 ; }
Count of Subsets containing only the given value K | C ++ implementation to find the number of subsets formed by the given value K ; Function to find the number of subsets formed by the given value K ; Count is used to maintain the number of continuous K 's ; Iterating through the array ; If the element in the array is equal to K ; count * ( count + 1 ) / 2 is the total number of subsets with only K as their element ; Change count to 0 because other element apart from K has been found ; To handle the last set of K 's ; Driver code
#include <iostream> NEW_LINE using namespace std ; int count ( int arr [ ] , int N , int K ) { int count = 0 , ans = 0 ; for ( int i = 0 ; i < N ; i ++ ) { if ( arr [ i ] == K ) { count = count + 1 ; } else { ans += ( count * ( count + 1 ) ) / 2 ; count = 0 ; } } ans = ans + ( count * ( count + 1 ) ) / 2 ; return ans ; } int main ( ) { int arr [ ] = { 1 , 0 , 0 , 1 , 1 , 0 , 0 } ; int N = sizeof ( arr ) / sizeof ( int ) ; int K = 0 ; cout << count ( arr , N , K ) ; }
Ternary number system or Base 3 numbers | C ++ program to convert decimal number to ternary number ; Function to convert a decimal number to a ternary number ; Base case ; Finding the remainder when N is divided by 3 ; Recursive function to call the function for the integer division of the value N / 3 ; Handling the negative cases ; Function to convert the decimal to ternary ; If the number is greater than 0 , compute the ternary representation of the number ; Driver code
#include <cstdio> NEW_LINE #include <iostream> NEW_LINE #include <math.h> NEW_LINE using namespace std ; void convertToTernary ( int N ) { if ( N == 0 ) return ; int x = N % 3 ; N /= 3 ; if ( x < 0 ) N += 1 ; convertToTernary ( N ) ; if ( x < 0 ) cout << x + ( 3 * -1 ) ; else cout << x ; } void convert ( int Decimal ) { cout << " Ternary ▁ number ▁ of ▁ " << Decimal << " ▁ is : ▁ " ; if ( Decimal != 0 ) { convertToTernary ( Decimal ) ; } else cout << "0" << endl ; } int main ( ) { int Decimal = 2747 ; convert ( Decimal ) ; return 0 ; }
Largest number less than or equal to Z that leaves a remainder X when divided by Y | C ++ implementation to Find the largest non - negative number that is less than or equal to integer Z and leaves a remainder X when divided by Y ; Function to get the number ; remainder can ' t ▁ be ▁ larger ▁ ▁ than ▁ the ▁ largest ▁ number , ▁ ▁ if ▁ so ▁ then ▁ answer ▁ doesn ' t exist . ; reduce number by x ; finding the possible number that is divisible by y ; this number is always <= x as we calculated over z - x ; Driver Code ; initialise the three integers
#include <bits/stdc++.h> NEW_LINE using namespace std ; int get ( int x , int y , int z ) { if ( x > z ) return -1 ; int val = z - x ; int div = ( z - x ) / y ; int ans = div * y + x ; return ans ; } int main ( ) { int x = 1 , y = 5 , z = 8 ; cout << get ( x , y , z ) << " STRNEWLINE " ; return 0 ; }
Find the conjugate of a Complex number | C ++ implementation to Find the conjugate of a complex number ; Function to find conjugate of a complex number ; store index of ' + ' ; store index of ' - ' ; print the result ; Driver code ; initialise the complex number
#include <bits/stdc++.h> NEW_LINE using namespace std ; void solve ( string s ) { string z = s ; int l = s . length ( ) ; int i ; if ( s . find ( ' + ' ) < l ) { i = s . find ( ' + ' ) ; replace ( s . begin ( ) , s . end ( ) , ' + ' , ' - ' ) ; } else { i = s . find ( ' - ' ) ; replace ( s . begin ( ) , s . end ( ) , ' - ' , ' + ' ) ; } cout << " Conjugate ▁ of ▁ " << z << " ▁ = ▁ " << s << endl ; } int main ( ) { string s = "3-4i " ; solve ( s ) ; return 0 ; }
Count of greater elements for each element in the Array | C ++ implementation of the above approach ; Store the frequency of the array elements ; Store the sum of frequency of elements greater than the current element ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void countOfGreaterElements ( int arr [ ] , int n ) { map < int , int > mp ; for ( int i = 0 ; i < n ; i ++ ) { mp [ arr [ i ] ] ++ ; } int x = 0 ; for ( auto it = mp . rbegin ( ) ; it != mp . rend ( ) ; it ++ ) { int temp = it -> second ; mp [ it -> first ] = x ; x += temp ; } for ( int i = 0 ; i < n ; i ++ ) cout << mp [ arr [ i ] ] << " ▁ " ; } int main ( ) { int arr [ ] = { 7 , 9 , 5 , 2 , 1 , 3 , 4 , 8 , 6 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; countOfGreaterElements ( arr , n ) ; return 0 ; }
Minimum operations required to make two numbers equal | C ++ program to find minimum operations required to make two numbers equal ; Function to return the minimum operations required ; Keeping B always greater ; Reduce B such that gcd ( A , B ) becomes 1. ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; long long int minOperations ( long long int A , long long int B ) { if ( A > B ) swap ( A , B ) ; B = B / __gcd ( A , B ) ; return B - 1 ; } int main ( ) { long long int A = 7 , B = 15 ; cout << minOperations ( A , B ) << endl ; return 0 ; }
Program to determine the Quadrant of a Complex number | C ++ program to determine the quadrant of a complex number ; Function to determine the quadrant of a complex number ; Storing the index of ' + ' ; Storing the index of ' - ' ; Finding the real part of the complex number ; Finding the imaginary part of the complex number ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void quadrant ( string s ) { int l = s . length ( ) ; int i ; if ( s . find ( ' + ' ) < l ) { i = s . find ( ' + ' ) ; } else { i = s . find ( ' - ' ) ; } string real = s . substr ( 0 , i ) ; string imaginary = s . substr ( i + 1 , l - 1 ) ; int x = stoi ( real ) ; int y = stoi ( imaginary ) ; if ( x > 0 and y > 0 ) cout << " Quadrant ▁ 1" ; else if ( x < 0 and y > 0 ) cout << " Quadrant ▁ 2" ; else if ( x < 0 and y < 0 ) cout << " Quadrant ▁ 3" ; else if ( x > 0 and y < 0 ) cout << " Quadrant ▁ 4" ; else if ( x == 0 and y > 0 ) cout << " Lies ▁ on ▁ positive " << " ▁ Imaginary ▁ axis " ; else if ( x == 0 and y < 0 ) cout << " Lies ▁ on ▁ negative " << " ▁ Imaginary ▁ axis " ; else if ( y == 0 and x < 0 ) cout << " Lies ▁ on ▁ negative " << " ▁ X - axis " ; else if ( y == 0 and x > 0 ) cout << " Lies ▁ on ▁ positive " << " ▁ X - axis " ; else cout << " Lies ▁ on ▁ the ▁ Origin " ; } int main ( ) { string s = "5 + 3i " ; quadrant ( s ) ; return 0 ; }
Sum and Product of all Fibonacci Nodes of a Singly Linked List | C ++ implementation to find the sum and product of all of the Fibonacci nodes in a singly linked list ; Node of the singly linked list ; Function to insert a node at the beginning of the singly Linked List ; Allocate new node ; Insert the data ; Link the old list to the new node ; Move the head to point the new node ; Function that returns the largest element from the linked list . ; Declare a max variable and initialize with INT_MIN ; Check loop while head not equal to NULL ; If max is less then head -> data then assign value of head -> data to max otherwise node points to next node . ; Function to create a hash table to check Fibonacci numbers ; Inserting the first two numbers in the hash ; Loop to add Fibonacci numbers upto the maximum element present in the linked list ; Function to find the required sum and product ; Find the largest node value in Singly Linked List ; Creating a set containing all the fibonacci numbers upto the maximum data value in the Singly Linked List ; Traverse the linked list ; If current node is fibonacci ; Find the sum and the product ; Driver code ; Create the linked list 15 -> 16 -> 8 -> 6 -> 13
#include <bits/stdc++.h> NEW_LINE using namespace std ; struct Node { int data ; Node * next ; } ; void push ( Node * * head_ref , int new_data ) { Node * new_node = ( Node * ) malloc ( sizeof ( struct Node ) ) ; new_node -> data = new_data ; new_node -> next = ( * head_ref ) ; ( * head_ref ) = new_node ; } int largestElement ( struct Node * head_ref ) { int max = INT_MIN ; Node * head = head_ref ; while ( head != NULL ) { if ( max < head -> data ) max = head -> data ; head = head -> next ; } return max ; } void createHash ( set < int > & hash , int maxElement ) { int prev = 0 , curr = 1 ; hash . insert ( prev ) ; hash . insert ( curr ) ; while ( curr <= maxElement ) { int temp = curr + prev ; hash . insert ( temp ) ; prev = curr ; curr = temp ; } } void sumAndProduct ( Node * head_ref ) { int maxEle = largestElement ( head_ref ) ; set < int > hash ; createHash ( hash , maxEle ) ; int prod = 1 ; int sum = 0 ; Node * ptr = head_ref ; while ( ptr != NULL ) { if ( hash . find ( ptr -> data ) != hash . end ( ) ) { prod *= ptr -> data ; sum += ptr -> data ; } ptr = ptr -> next ; } cout << " Sum ▁ = ▁ " << sum << endl ; cout << " Product ▁ = ▁ " << prod ; } int main ( ) { Node * head = NULL ; push ( & head , 13 ) ; push ( & head , 6 ) ; push ( & head , 8 ) ; push ( & head , 16 ) ; push ( & head , 15 ) ; sumAndProduct ( head ) ; return 0 ; }
Product of all Subarrays of an Array | C ++ program to find product of all subarray of an array ; Function to find product of all subarrays ; Variable to store the product ; Compute the product while traversing for subarrays ; Printing product of all subarray ; Driver code ; Function call
#include <bits/stdc++.h> NEW_LINE using namespace std ; void product_subarrays ( int arr [ ] , int n ) { int product = 1 ; for ( int i = 0 ; i < n ; i ++ ) { for ( int j = i ; j < n ; j ++ ) { for ( int k = i ; k <= j ; k ++ ) product *= arr [ k ] ; } } cout << product << " STRNEWLINE " ; } int main ( ) { int arr [ ] = { 10 , 3 , 7 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; product_subarrays ( arr , n ) ; return 0 ; }
Check if a N base number is Even or Odd | C ++ code to check if a Octal number is Even or Odd ; To return value of a char . ; Function to convert a number from N base to decimal ; power of base ; Decimal equivalent is str [ len - 1 ] * 1 + str [ len - 1 ] * base + str [ len - 1 ] * ( base ^ 2 ) + ... ; A digit in input number must be less than number 's base ; Returns true if n is even , else odd ; Driver code
#include <iostream> NEW_LINE using namespace std ; int val ( char c ) { if ( c >= '0' && c <= '9' ) return ( int ) c - '0' ; else return ( int ) c - ' A ' + 10 ; } int toDeci ( string str , int base ) { int len = str . length ( ) ; int power = 1 ; int num = 0 ; int i ; for ( i = len - 1 ; i >= 0 ; i -- ) { if ( val ( str [ i ] ) >= base ) { cout << " Invalid ▁ Number " ; return -1 ; } num += val ( str [ i ] ) * power ; power = power * base ; } return num ; } bool isEven ( string num , int N ) { int deci = toDeci ( num , N ) ; return ( deci % 2 == 0 ) ; } int main ( ) { string num = "11A " ; int N = 16 ; if ( isEven ( num , N ) ) { cout << " Even " ; } else { cout << " Odd " ; } }
Find the next Factorial greater than N | C ++ implementation of the above approach ; Array that stores the factorial till 20 ; Function to pre - compute the factorial till 20 ; Precomputing factorials ; Function to return the next factorial number greater than N ; Traverse the factorial array ; Find the next just greater factorial than N ; Driver Code ; Function to precalculate the factorial till 20 ; Function call
#include " bits / stdc + + . h " NEW_LINE using namespace std ; long long fact [ 21 ] ; void preCompute ( ) { fact [ 0 ] = 1 ; for ( int i = 1 ; i < 18 ; i ++ ) fact [ i ] = ( fact [ i - 1 ] * i ) ; } void nextFactorial ( int N ) { for ( int i = 0 ; i < 21 ; i ++ ) { if ( N < fact [ i ] ) { cout << fact [ i ] ; break ; } } } int main ( ) { preCompute ( ) ; int N = 120 ; nextFactorial ( N ) ; return 0 ; }
Find K distinct positive odd integers with sum N | C ++ implementation to find K odd positive integers such that their sum is equal to given number ; Function to find K odd positive integers such that their sum is N ; Condition to check if there are enough values to check ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; #define ll long long int NEW_LINE void findDistinctOddSum ( ll n , ll k ) { if ( ( k * k ) <= n && ( n + k ) % 2 == 0 ) { int val = 1 ; int sum = 0 ; for ( int i = 1 ; i < k ; i ++ ) { cout << val << " ▁ " ; sum += val ; val += 2 ; } cout << n - sum << endl ; } else cout << " NO ▁ STRNEWLINE " ; } int main ( ) { ll n = 100 ; ll k = 4 ; findDistinctOddSum ( n , k ) ; return 0 ; }
Minimum number of operations to convert array A to array B by adding an integer into a subarray | C ++ implementation to find the minimum number of operations in which the array A can be converted to another array B ; Function to find the minimum number of operations in which array A can be converted to array B ; Loop to iterate over the array ; if both elements are equal then move to next element ; Calculate the difference between two elements ; loop while the next pair of elements have same difference ; Increase the number of operations by 1 ; Print the number of operations required ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void checkArray ( int a [ ] , int b [ ] , int n ) { int operations = 0 ; int i = 0 ; while ( i < n ) { if ( a [ i ] - b [ i ] == 0 ) { i ++ ; continue ; } int diff = a [ i ] - b [ i ] ; i ++ ; while ( i < n && a [ i ] - b [ i ] == diff ) { i ++ ; } operations ++ ; } cout << operations << " STRNEWLINE " ; } int main ( ) { int a [ ] = { 3 , 7 , 1 , 4 , 1 , 2 } ; int b [ ] = { 3 , 7 , 3 , 6 , 3 , 2 } ; int size = sizeof ( a ) / sizeof ( a [ 0 ] ) ; checkArray ( a , b , size ) ; return 0 ; }
Perfect Cube | C ++ program to check if a number is a perfect cube using prime factors ; Inserts the prime factor in HashMap if not present if present updates it 's frequency ; A utility function to find all prime factors of a given number N ; Insert the number of 2 s that divide n ; n must be odd at this point So we can skip one element ; while i divides n , insert i and divide n ; This condition is to handle the case when n is a prime number greater than 2 ; Function to check if a number is perfect cube ; Iteration in Map ; Driver Code ; Function to check if N is perfect cube or not
#include <bits/stdc++.h> NEW_LINE using namespace std ; map < int , int > insertPF ( map < int , int > primeFact , int fact ) { if ( primeFact . find ( fact ) != primeFact . end ( ) ) { primeFact [ fact ] ++ ; } else { primeFact [ fact ] = 1 ; } return primeFact ; } map < int , int > primeFactors ( int n ) { map < int , int > primeFact ; while ( n % 2 == 0 ) { primeFact = insertPF ( primeFact , 2 ) ; n /= 2 ; } for ( int i = 3 ; i <= sqrt ( n ) ; i += 2 ) { while ( n % i == 0 ) { primeFact = insertPF ( primeFact , i ) ; n /= i ; } } if ( n > 2 ) primeFact = insertPF ( primeFact , n ) ; return primeFact ; } string perfectCube ( int n ) { map < int , int > primeFact ; primeFact = primeFactors ( n ) ; for ( auto x : primeFact ) { if ( x . second % 3 != 0 ) return " No " ; } return " Yes " ; } int main ( ) { int N = 216 ; cout << perfectCube ( N ) ; return 0 ; }
Count ways to reach the Nth stair using multiple 1 or 2 steps and a single step 3 | C ++ implementation to find the number the number of ways to reach Nth stair by taking 1 or 2 steps at a time and 3 rd step exactly once ; Single line to find factorial ; Function to find the number of ways ; Base Case ; Count of 2 - steps ; Count of 1 - steps ; Initial length of sequence ; Expected count of 2 - steps ; Loop to find the ways for every possible sequence ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int factorial ( int n ) { return ( n == 1 n == 0 ) ? 1 : n * factorial ( n - 1 ) ; } int ways ( int n ) { if ( n < 3 ) { return 0 ; } int c2 = 0 ; int c1 = n - 3 ; int l = c1 + 1 ; int s = 0 ; int exp_c2 = c1 / 2 ; while ( exp_c2 >= c2 ) { int f1 = factorial ( l ) ; int f2 = factorial ( c1 ) ; int f3 = factorial ( c2 ) ; int f4 = ( f2 * f3 ) ; s += f1 / f4 ; c2 += 1 ; c1 -= 2 ; l -= 1 ; } return s ; } int main ( ) { int n = 7 ; int ans = ways ( n ) ; cout << ans << endl ; return 0 ; }
Find N from the value of N ! | C ++ program to find a number such that the factorial of that number is given ; Map to precompute and store the factorials of the numbers ; Function to precompute factorial ; Calculating the factorial for each i and storing in a map ; Driver code ; Precomputing the factorials
#include " bits / stdc + + . h " NEW_LINE #define ll long long int NEW_LINE using namespace std ; map < ll , ll > m ; int precompute ( ) { ll fact = 1 ; for ( ll i = 1 ; i <= 18 ; i ++ ) { fact = fact * i ; m [ fact ] = i ; } } int main ( ) { precompute ( ) ; int K = 120 ; cout << m [ K ] << endl ; K = 6 ; cout << m [ K ] << endl ; return 0 ; }
Count of Leap Years in a given year range | C ++ implementation to find the count of leap years in given range of the year ; Function to calculate the number of leap years in range of ( 1 , year ) ; Function to calculate the number of leap years in given range ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int calNum ( int year ) { return ( year / 4 ) - ( year / 100 ) + ( year / 400 ) ; } void leapNum ( int l , int r ) { l -- ; int num1 = calNum ( r ) ; int num2 = calNum ( l ) ; cout << num1 - num2 << endl ; } int main ( ) { int l1 = 1 , r1 = 400 ; leapNum ( l1 , r1 ) ; int l2 = 400 , r2 = 2000 ; leapNum ( l2 , r2 ) ; return 0 ; }
Ternary representation of Cantor set | C ++ implementation to find the cantor set for n levels and for a given start_num and end_num ; The Linked List Structure for the Cantor Set ; Function to initialize the Cantor Set List ; Function to propogate the list by adding new nodes for the next levels ; Modifying the start and end values for the next level ; Changing the pointers to the next node ; Recursively call the function to generate the Cantor Set for the entire level ; Function to print a level of the Set ; Function to build and display the Cantor Set for each level ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; typedef struct cantor { double start , end ; struct cantor * next ; } Cantor ; Cantor * startList ( Cantor * head , double start_num , double end_num ) { if ( head == NULL ) { head = new Cantor ; head -> start = start_num ; head -> end = end_num ; head -> next = NULL ; } return head ; } Cantor * propagate ( Cantor * head ) { Cantor * temp = head ; if ( temp != NULL ) { Cantor * newNode = new Cantor ; double diff = ( ( ( temp -> end ) - ( temp -> start ) ) / 3 ) ; newNode -> end = temp -> end ; temp -> end = ( ( temp -> start ) + diff ) ; newNode -> start = ( newNode -> end ) - diff ; newNode -> next = temp -> next ; temp -> next = newNode ; propagate ( temp -> next -> next ) ; } return head ; } void print ( Cantor * temp ) { while ( temp != NULL ) { printf ( " [ % lf ] ▁ - - ▁ [ % lf ] TABSYMBOL " , temp -> start , temp -> end ) ; temp = temp -> next ; } cout << endl ; } void buildCantorSet ( int A , int B , int L ) { Cantor * head = NULL ; head = startList ( head , A , B ) ; for ( int i = 0 ; i < L ; i ++ ) { cout << " Level _ " << i << " ▁ : ▁ " ; print ( head ) ; propagate ( head ) ; } cout << " Level _ " << L << " ▁ : ▁ " ; print ( head ) ; } int main ( ) { int A = 0 ; int B = 9 ; int L = 2 ; buildCantorSet ( A , B , L ) ; return 0 ; }
Find sum of f ( s ) for all the chosen sets from the given array | 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 sum of f ( s ) for all the chosen sets from the given array ; Sort the given array ; Calculate the factorial and modinverse of all elements ; For all the possible sets Calculate max ( S ) and min ( S ) ; Driver code
#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 ; } int max_min ( int a [ ] , int n , int k ) { sort ( a , a + n ) ; factorialfun ( ) ; modinversefun ( ) ; long long ans = 0 ; k -- ; for ( int i = 0 ; i < n ; i ++ ) { int x = n - i - 1 ; if ( x >= k ) ans -= binomial ( x , k ) * a [ i ] % mod ; int y = i ; if ( y >= k ) ans += binomial ( y , k ) * a [ i ] % mod ; ans = ( ans + mod ) % mod ; } return ( int ) ( ans ) ; } int main ( ) { int a [ ] = { 1 , 1 , 3 , 4 } , k = 2 ; int n = sizeof ( a ) / sizeof ( int ) ; cout << max_min ( a , n , k ) ; return 0 ; }
Length of Smallest subarray in range 1 to N with sum greater than a given value | C ++ implementation of the above implementation ; Function to return the count of minimum elements such that the sum of those elements is > S . ; Initialize currentSum = 0 ; Loop from N to 1 to add the numbers and check the condition . ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int countNumber ( int N , int S ) { int countElements = 0 ; int currSum = 0 ; while ( currSum <= S ) { currSum += N ; N -- ; countElements ++ ; } return countElements ; } int main ( ) { int N , S ; N = 5 ; S = 11 ; int count = countNumber ( N , S ) ; cout << count << endl ; return 0 ; }
Next Number with distinct digits | C ++ program to find next consecutive Number with all distinct digits ; Function to count distinct digits in a number ; To count the occurrence of digits in number from 0 to 9 ; Iterate over the digits of the number Flag those digits as found in the array ; Traverse the array arr and count the distinct digits in the array ; Function to return the total number of digits in the number ; Iterate over the digits of the number ; Function to return the next number with distinct digits ; Count the distinct digits in N + 1 ; Count the total number of digits in N + 1 ; Return the next consecutive number ; Increment Number by 1 ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int countDistinct ( int n ) { int arr [ 10 ] = { 0 } ; int count = 0 ; while ( n ) { int r = n % 10 ; arr [ r ] = 1 ; n /= 10 ; } for ( int i = 0 ; i < 10 ; i ++ ) { if ( arr [ i ] ) count ++ ; } return count ; } int countDigit ( int n ) { int c = 0 ; while ( n ) { int r = n % 10 ; c ++ ; n /= 10 ; } return c ; } int nextNumberDistinctDigit ( int n ) { while ( n < INT_MAX ) { int distinct_digits = countDistinct ( n + 1 ) ; int total_digits = countDigit ( n + 1 ) ; if ( distinct_digits == total_digits ) { return n + 1 ; } else n ++ ; } return -1 ; } int main ( ) { int n = 2019 ; cout << nextNumberDistinctDigit ( n ) ; return 0 ; }
Minimum possible sum of array B such that AiBi = AjBj for all 1 Γ’ ‰€ i < j Γ’ ‰€ N | C ++ implementation of the approach ; To store least prime factors of all the numbers ; Function to find the least prime factor of all the numbers ; Function to return the ( ( a ^ m1 ) % mod ) ; Function to return the sum of elements of array B ; Find the prime factors of all the numbers ; To store each prime count in lcm ; Current number ; Map to store the prime count of a single number ; Basic way to calculate all prime factors ; If it is the first number in the array ; Take the maximum count of prime in a number ; Calculate lcm of given array ; Calculate sum of elements of array B ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; #define mod (int)(1e9 + 7) NEW_LINE #define N 1000005 NEW_LINE int lpf [ N ] ; void least_prime_factor ( ) { for ( int i = 1 ; i < N ; i ++ ) lpf [ i ] = i ; for ( int i = 2 ; i < N ; i ++ ) if ( lpf [ i ] == i ) for ( int j = i * 2 ; j < N ; j += i ) if ( lpf [ j ] == j ) lpf [ j ] = i ; } 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 ; } long long sum_of_elements ( int a [ ] , int n ) { least_prime_factor ( ) ; map < int , int > prime_factor ; for ( int i = 0 ; i < n ; i ++ ) { int temp = a [ i ] ; map < int , int > single_number ; while ( temp > 1 ) { int x = lpf [ temp ] ; single_number [ x ] ++ ; temp /= x ; } if ( i == 0 ) prime_factor = single_number ; else { for ( auto x : single_number ) prime_factor [ x . first ] = max ( x . second , prime_factor [ x . first ] ) ; } } long long ans = 0 , lcm = 1 ; for ( auto x : prime_factor ) lcm = ( lcm * power ( x . first , x . second ) ) % mod ; for ( int i = 0 ; i < n ; i ++ ) ans = ( ans + ( lcm * power ( a [ i ] , mod - 2 ) ) % mod ) % mod ; return ans ; } int main ( ) { int a [ ] = { 2 , 3 , 4 } ; int n = sizeof ( a ) / sizeof ( int ) ; cout << sum_of_elements ( a , n ) ; return 0 ; }
Find Number of Even cells in a Zero Matrix after Q queries | C ++ program find Number of Even cells in a Zero Matrix after Q queries ; Function to find the number of even cell in a 2D matrix ; Maintain two arrays , one for rows operation and one for column operation ; Increment operation on row [ i ] ; Increment operation on col [ i ] ; Count odd and even values in both arrays and multiply them ; Count of rows having even numbers ; Count of rows having odd numbers ; Count of columns having even numbers ; Count of columns having odd numbers ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int findNumberOfEvenCells ( int n , int q [ ] [ 2 ] , int size ) { int row [ n ] = { 0 } ; int col [ n ] = { 0 } ; for ( int i = 0 ; i < size ; i ++ ) { int x = q [ i ] [ 0 ] ; int y = q [ i ] [ 1 ] ; row [ x - 1 ] ++ ; col [ y - 1 ] ++ ; } int r1 = 0 , r2 = 0 ; int c1 = 0 , c2 = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( row [ i ] % 2 == 0 ) { r1 ++ ; } if ( row [ i ] % 2 == 1 ) { r2 ++ ; } if ( col [ i ] % 2 == 0 ) { c1 ++ ; } if ( col [ i ] % 2 == 1 ) { c2 ++ ; } } int count = r1 * c1 + r2 * c2 ; return count ; } int main ( ) { int n = 2 ; int q [ ] [ 2 ] = { { 1 , 1 } , { 1 , 2 } , { 2 , 1 } } ; int size = sizeof ( q ) / sizeof ( q [ 0 ] ) ; cout << findNumberOfEvenCells ( n , q , size ) ; return 0 ; }
Find maximum unreachable height using two ladders | C ++ implementation of the approach ; Function to return the maximum height which can 't be reached ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int maxHeight ( int h1 , int h2 ) { return ( ( h1 * h2 ) - h1 - h2 ) ; } int main ( ) { int h1 = 7 , h2 = 5 ; cout << max ( 0 , maxHeight ( h1 , h2 ) ) ; return 0 ; }
Fermat 's Factorization Method | C ++ implementation of fermat 's factorization ; This function finds the value of a and b and returns a + b and a - b ; since fermat 's factorization applicable for odd positive integers only ; check if n is a even number ; if n is a perfect root , then both its square roots are its factors ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void FermatFactors ( int n ) { if ( n <= 0 ) { cout << " [ " << n << " ] " ; return ; } if ( ( n & 1 ) == 0 ) { cout << " [ " << n / 2.0 << " , " << 2 << " ] " ; return ; } int a = ceil ( sqrt ( n ) ) ; if ( a * a == n ) { cout << " [ " << a << " , " << a << " ] " ; return ; } int b ; while ( true ) { int b1 = a * a - n ; b = ( int ) sqrt ( b1 ) ; if ( b * b == b1 ) break ; else a += 1 ; } cout << " [ " << ( a - b ) << " , " << ( a + b ) << " ] " ; return ; } int main ( ) { FermatFactors ( 6557 ) ; return 0 ; }
Append two elements to make the array satisfy the given condition | C ++ implementation of the approach ; Function to find the required numbers ; Find the sum and xor ; Print the required elements ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void findNums ( int arr [ ] , int n ) { int S = 0 , X = 0 ; for ( int i = 0 ; i < n ; i ++ ) { S += arr [ i ] ; X ^= arr [ i ] ; } cout << X << " ▁ " << ( X + S ) ; } int main ( ) { int arr [ ] = { 1 , 7 } ; int n = sizeof ( arr ) / sizeof ( int ) ; findNums ( arr , n ) ; return 0 ; }
Satisfy the parabola when point ( A , B ) and the equation is given | C ++ implementation of the approach ; Function to find the required values ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void solve ( int A , int B ) { double p = B / 2.0 ; int M = ceil ( 4 * p ) ; int N = 1 ; int O = - 2 * A ; int Q = ceil ( A * A + 4 * p * p ) ; cout << M << " ▁ " << N << " ▁ " << O << " ▁ " << Q ; } int main ( ) { int a = 1 ; int b = 1 ; solve ( a , b ) ; }
Largest number dividing maximum number of elements in the array | C ++ implementation of the approach ; Function to return the largest number that divides the maximum elements from the given array ; Finding gcd of all the numbers in the array ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int findLargest ( int * arr , int n ) { int gcd = 0 ; for ( int i = 0 ; i < n ; i ++ ) gcd = __gcd ( arr [ i ] , gcd ) ; return gcd ; } int main ( ) { int arr [ ] = { 3 , 6 , 9 } ; int n = sizeof ( arr ) / sizeof ( int ) ; cout << findLargest ( arr , n ) ; return 0 ; }
Check if the sum of digits of N is palindrome | C ++ implementation of the approach ; Function to return the sum of digits of n ; Function that returns true if n is palindrome ; Find the appropriate divisor to extract the leading digit ; If first and last digit not same return false ; Removing the leading and trailing digit from number ; Reducing divisor by a factor of 2 as 2 digits are dropped ; Function that returns true if the digit sum of n is palindrome ; Sum of the digits of n ; If the digit sum is palindrome ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int digitSum ( int n ) { int sum = 0 ; while ( n > 0 ) { sum += ( n % 10 ) ; n /= 10 ; } return sum ; } bool isPalindrome ( int n ) { int divisor = 1 ; while ( n / divisor >= 10 ) divisor *= 10 ; while ( n != 0 ) { int leading = n / divisor ; int trailing = n % 10 ; if ( leading != trailing ) return false ; n = ( n % divisor ) / 10 ; divisor = divisor / 100 ; } return true ; } bool isDigitSumPalindrome ( int n ) { int sum = digitSum ( n ) ; if ( isPalindrome ( sum ) ) return true ; return false ; } int main ( ) { int n = 56 ; if ( isDigitSumPalindrome ( n ) ) cout << " Yes " ; else cout << " No " ; 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 ; If k is odd the answer is the number itself ; Else the answer is 0 ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int xorK ( int n , int k ) { if ( k % 2 == 1 ) return n ; return 0 ; } int main ( ) { int n = 123 , k = 3 ; cout << xorK ( n , k ) ; return 0 ; }
Find the sum of the costs of all possible arrangements of the cells | C ++ implementation of the approach ; To store the factorials and factorial mod inverse of the numbers ; Function to return ( a ^ m1 ) % mod ; Function to find the factorials of all the numbers ; Function to find factorial mod inverse of all the numbers ; Function to return nCr ; Function to return the sum of the costs of all the possible arrangements of the cells ; For all possible X 's ; For all possible Y 's ; Driver code
#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 ; } int arrange ( int n , int m , int k ) { factorialfun ( ) ; modinversefun ( ) ; long long ans = 0 ; for ( int i = 1 ; i < n ; i ++ ) ans += ( 1LL * i * ( n - i ) * m * m ) % mod ; for ( int i = 1 ; i < m ; i ++ ) ans += ( 1LL * i * ( m - i ) * n * n ) % mod ; ans = ( ans * binomial ( n * m - 2 , k - 2 ) ) % mod ; return ( int ) ans ; } int main ( ) { int n = 2 , m = 2 , k = 2 ; cout << arrange ( n , m , k ) ; return 0 ; }
Find the Nth digit in the proper fraction of two numbers | C ++ implementation of the approach ; Function to print the Nth digit in the fraction ( p / q ) ; To store the resultant digit ; While N > 0 compute the Nth digit by dividing p and q and store the result into variable res and go to next digit ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int findNthDigit ( int p , int q , int N ) { int res ; while ( N > 0 ) { N -- ; p *= 10 ; res = p / q ; p %= q ; } return res ; } int main ( ) { int p = 1 , q = 2 , N = 1 ; cout << findNthDigit ( p , q , N ) ; 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 ; Subtract the subarray sum ; Sum of subarray arr [ i ... n - 1 ] ; 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 ) { int subSum = arr [ n - 1 ] ; for ( int i = n - 2 ; i >= 0 ; i -- ) { int curr = arr [ i ] ; arr [ i ] -= subSum ; subSum += curr ; } 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 closest integer with the same weight | C ++ implementation of the approach ; Function to return the number closest to x which has equal number of set bits as x ; Loop for each bit in x and compare with the next bit ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; const int NumUnsignBits = 64 ; unsigned long findNum ( unsigned long x ) { for ( int i = 0 ; i < NumUnsignBits - 1 ; i ++ ) { if ( ( ( x >> i ) & 1 ) != ( ( x >> ( i + 1 ) ) & 1 ) ) { x ^= ( 1 << i ) | ( 1 << ( i + 1 ) ) ; return x ; } } } int main ( ) { int n = 92 ; cout << findNum ( n ) ; return 0 ; }
Cake Distribution Problem | C ++ implementation of the approach ; Function to return the remaining count of cakes ; Sum for 1 cycle ; no . of full cycle and remainder ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int cntCakes ( int n , int m ) { int sum = ( n * ( n + 1 ) ) / 2 ; int quo = m / sum ; int rem = m % sum ; double ans = m - quo * sum ; double x = ( -1 + pow ( ( 8 * rem ) + 1 , 0.5 ) ) / 2 ; ans = ans - x * ( x + 1 ) / 2 ; return int ( ans ) ; } int main ( ) { int n = 3 ; int m = 8 ; int ans = cntCakes ( n , m ) ; cout << ( ans ) ; }
Find the number of squares inside the given square grid | C ++ implementation of the approach ; Function to return the number of squares inside an n * n grid ; Driver code
#include <iostream> NEW_LINE using namespace std ; int cnt_squares ( int n ) { return n * ( n + 1 ) * ( 2 * n + 1 ) / 6 ; } int main ( ) { cout << cnt_squares ( 4 ) << endl ; return 0 ; }
Find all palindrome numbers of given digits | C ++ implementation of the approach ; Function to return the reverse of num ; Function that returns true if num is palindrome ; If the number is equal to the reverse of it then it is a palindrome ; Function to print all the d - digit palindrome numbers ; Smallest and the largest d - digit numbers ; Starting from the smallest d - digit number till the largest ; If the current number is palindrome ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int reverse ( int num ) { int rev = 0 ; while ( num > 0 ) { rev = rev * 10 + num % 10 ; num = num / 10 ; } return rev ; } bool isPalindrome ( int num ) { if ( num == reverse ( num ) ) return true ; return false ; } void printPalindromes ( int d ) { if ( d <= 0 ) return ; int smallest = pow ( 10 , d - 1 ) ; int largest = pow ( 10 , d ) - 1 ; for ( int i = smallest ; i <= largest ; i ++ ) { if ( isPalindrome ( i ) ) cout << i << " ▁ " ; } } int main ( ) { int d = 2 ; printPalindromes ( d ) ; return 0 ; }
Find X and Y intercepts of a line passing through the given points | C ++ implementation of the approach ; Function to find the X and Y intercepts of the line passing through the given points ; if line is parallel to y axis ; x - intercept will be p [ 0 ] ; y - intercept will be infinity ; if line is parallel to x axis ; x - intercept will be infinity ; y - intercept will be p [ 1 ] ; Slope of the line ; y = mx + c in where c is unknown Use any of the given point to find c ; For finding the x - intercept put y = 0 ; For finding the y - intercept put x = 0 ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void getXandYintercept ( int P [ ] , int Q [ ] ) { int a = P [ 1 ] - Q [ 1 ] ; int b = P [ 0 ] - Q [ 0 ] ; if ( b == 0 ) { cout << P [ 0 ] << endl ; cout << " infinity " ; return ; } if ( a == 0 ) { cout << " infinity " ; cout << P [ 1 ] << endl ; return ; } double m = a / ( b * 1.0 ) ; int x = P [ 0 ] ; int y = P [ 1 ] ; double c = y - m * x ; y = 0 ; double r = ( y - c ) / ( m * 1.0 ) ; cout << r << endl ; x = 0 ; y = m * x + c ; printf ( " % .8f " , c ) ; } int main ( ) { int p1 [ ] = { 5 , 2 } ; int p2 [ ] = { 2 , 7 } ; getXandYintercept ( p1 , p2 ) ; return 0 ; }
Minimum number of moves to reach N starting from ( 1 , 1 ) | C ++ implementation of the approach ; Function to return the minimum number of moves required to reach the cell containing N starting from ( 1 , 1 ) ; To store the required answer ; For all possible values of divisors ; If i is a divisor of n ; Get the moves to reach n ; Return the required answer ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int min_moves ( int n ) { int ans = INT_MAX ; for ( int i = 1 ; i * i <= n ; i ++ ) { if ( n % i == 0 ) { ans = min ( ans , i + n / i - 2 ) ; } } return ans ; } int main ( ) { int n = 10 ; cout << min_moves ( n ) ; return 0 ; }
Minimum possible value of ( i * j ) % 2019 | C ++ implementation of the approach ; Function to return the minimum possible value of ( i * j ) % 2019 ; If we can get a number divisible by 2019 ; Find the minimum value by running nested loops ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; const int MOD = 2019 ; int min_modulo ( int l , int r ) { if ( r - l >= MOD ) return 0 ; else { int ans = MOD - 1 ; for ( int i = l ; i <= r ; i ++ ) { for ( int j = i + 1 ; j <= r ; j ++ ) { ans = min ( ans , ( i * j ) % MOD ) ; } } return ans ; } } int main ( ) { int l = 2020 , r = 2040 ; cout << min_modulo ( l , r ) ; return 0 ; }
Represent ( 2 / N ) as the sum of three distinct positive integers of the form ( 1 / m ) | C ++ implementation of the approach ; Function to find the required fractions ; Base condition ; For N > 1 ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void find_numbers ( int N ) { if ( N == 1 ) { cout << -1 ; } else { cout << N << " ▁ " << N + 1 << " ▁ " << N * ( N + 1 ) ; } } int main ( ) { int N = 5 ; find_numbers ( N ) ; return 0 ; }
Count the pairs in an array such that the difference between them and their indices is equal | C ++ implementation of the approach ; Function to return the count of all valid pairs ; To store the frequencies of ( arr [ i ] - i ) ; To store the required count ; If cnt is the number of elements whose difference with their index is same then ( ( cnt * ( cnt - 1 ) ) / 2 ) such pairs are possible ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int countPairs ( int arr [ ] , int n ) { unordered_map < int , int > map ; for ( int i = 0 ; i < n ; i ++ ) map [ arr [ i ] - i ] ++ ; int res = 0 ; for ( auto x : map ) { int cnt = x . second ; res += ( ( cnt * ( cnt - 1 ) ) / 2 ) ; } return res ; } int main ( ) { int arr [ ] = { 1 , 5 , 6 , 7 , 9 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << countPairs ( arr , n ) ; return 0 ; }
Minimum possible number with the given operation | C ++ implementation of the approach ; Function to return the minimum possible integer that can be obtained from the given integer after performing the given operations ; For every digit ; Digits less than 5 need not to be changed as changing them will lead to a larger number ; The resulting integer cannot have leading zero ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; string minInt ( string str ) { for ( int i = 0 ; i < str . length ( ) ; i ++ ) { if ( str [ i ] >= '5' ) { str [ i ] = ( '9' - str [ i ] ) + '0' ; } } if ( str [ 0 ] == '0' ) str [ 0 ] = '9' ; return str ; } int main ( ) { string str = "589" ; cout << minInt ( str ) ; return 0 ; }
Reduce N to 1 with minimum number of given operations | C ++ implementation of the approach ; Function to return the minimum number of given operations required to reduce n to 1 ; To store the count of operations ; To store the digit ; If n is already then no operation is required ; Extract all the digits except the first digit ; Store the maximum of that digits ; for each digit ; First digit ; Add the value to count ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; long long int minOperations ( long long int n ) { long long int count = 0 ; long long int d = 0 ; if ( n == 1 ) return 0 ; while ( n > 9 ) { d = max ( n % 10 , d ) ; n /= 10 ; count += 10 ; } d = max ( d , n - 1 ) ; count += abs ( d ) ; return count - 1 ; } int main ( ) { long long int n = 240 ; cout << minOperations ( n ) ; return 0 ; }
Find the largest number that can be formed by changing at most K digits | C ++ implementation of the approach ; Function to return the maximum number that can be formed by changing at most k digits in str ; For every digit of the number ; If no more digits can be replaced ; If current digit is not already 9 ; Replace it with 9 ; One digit has been used ; Driver code
#include <iostream> NEW_LINE using namespace std ; string findMaximumNum ( string str , int n , int k ) { for ( int i = 0 ; i < n ; i ++ ) { if ( k < 1 ) break ; if ( str [ i ] != '9' ) { str [ i ] = '9' ; k -- ; } } return str ; } int main ( ) { string str = "569431" ; int n = str . length ( ) ; int k = 3 ; cout << findMaximumNum ( str , n , k ) ; return 0 ; }
Check if two Integer are anagrams of each other | C ++ implementation of the approach ; Function that returns true if a and b are anagarams of each other ; Converting numbers to strings ; Checking if the sorting values of two strings are equal ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool areAnagrams ( int a , int b ) { string c = to_string ( a ) ; string d = to_string ( b ) ; sort ( c . begin ( ) , c . end ( ) ) ; sort ( d . begin ( ) , d . end ( ) ) ; if ( c == d ) return true ; else return false ; } int main ( ) { int a = 240 ; int b = 204 ; if ( areAnagrams ( a , b ) ) cout << " Yes " ; else cout << " No " ; }
Number of occurrences of a given angle formed using 3 vertices of a n | C ++ implementation of the approach ; Function that calculates occurrences of given angle that can be created using any 3 sides ; Maximum angle in a regular n - gon is equal to the interior angle If the given angle is greater than the interior angle then the given angle cannot be created ; The given angle times n should be divisible by 180 else it cannot be created ; Initialise answer ; Calculate the frequency of given angle for each vertex ; Multiply answer by frequency . ; Multiply answer by the number of vertices . ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int solve ( int ang , int n ) { if ( ( ang * n ) > ( 180 * ( n - 2 ) ) ) { return 0 ; } else if ( ( ang * n ) % 180 != 0 ) { return 0 ; } int ans = 1 ; int freq = ( ang * n ) / 180 ; ans = ans * ( n - 1 - freq ) ; ans = ans * n ; return ans ; } int main ( ) { int ang = 90 , n = 4 ; cout << solve ( ang , n ) ; return 0 ; }
Find third number such that sum of all three number becomes prime | C ++ implementation of the above approach ; Function that will check whether number is prime or not ; Function to print the 3 rd number ; If the sum is odd ; If sum is not prime ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool prime ( int n ) { for ( int i = 2 ; i * i <= n ; i ++ ) { if ( n % i == 0 ) return false ; } return true ; } void thirdNumber ( int a , int b ) { int sum = 0 , temp = 0 ; sum = a + b ; temp = 1 ; if ( sum & 1 ) { temp = 2 ; } while ( ! prime ( sum + temp ) ) { temp += 2 ; } cout << temp ; } int main ( ) { int a = 3 , b = 5 ; thirdNumber ( a , b ) ; return 0 ; }
Total ways of selecting a group of X men from N men with or without including a particular man | C ++ implementation of the approach ; Function to return the value of nCr ; Initialize the answer ; Divide simultaneously by i to avoid overflow ; Function to return the count of ways ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int nCr ( int n , int r ) { int ans = 1 ; for ( int i = 1 ; i <= r ; i += 1 ) { ans *= ( n - r + i ) ; ans /= i ; } return ans ; } int total_ways ( int N , int X ) { return ( nCr ( N - 1 , X - 1 ) + nCr ( N - 1 , X ) ) ; } int main ( ) { int N = 5 , X = 3 ; cout << total_ways ( N , X ) ; return 0 ; }
Compute the maximum power with a given condition | Compute maximum power to which K can be raised so that given condition remains true ; Function to return the largest power ; If n is greater than given M ; If n == m ; Checking for the next power ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; #define ll long long NEW_LINE int calculate ( ll int n , ll int k , ll int m , ll int power ) { if ( n > m ) { if ( power == 0 ) return 0 ; else return power - 1 ; } else if ( n == m ) return power ; else return calculate ( n * k , k , m , power + 1 ) ; } int main ( ) { ll N = 1 , K = 2 , M = 5 ; cout << calculate ( N , K , M , 0 ) ; return 0 ; }
Program to find the number from given holes | C ++ implementation of the above approach ; Function that will find out the number ; If number of holes equal 0 then return 1 ; If number of holes equal 0 then return 0 ; If number of holes is more than 0 or 1. ; If number of holes is odd ; Driver code ; Calling Function
#include <bits/stdc++.h> NEW_LINE using namespace std ; void printNumber ( int holes ) { if ( holes == 0 ) cout << "1" ; else if ( holes == 1 ) cout << "0" ; else { int rem = 0 , quo = 0 ; rem = holes % 2 ; quo = holes / 2 ; if ( rem == 1 ) cout << "4" ; for ( int i = 0 ; i < quo ; i ++ ) cout << "8" ; } } int main ( ) { int holes = 3 ; printNumber ( holes ) ; return 0 ; }
Minimum cost to make all array elements equal | C ++ implementation of the approach ; Function to return the minimum cost to make each array element equal ; To store the count of even numbers present in the array ; To store the count of odd numbers present in the array ; Iterate through the array and find the count of even numbers and odd numbers ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int minCost ( int arr [ ] , int n ) { int count_even = 0 ; int count_odd = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( arr [ i ] % 2 == 0 ) count_even ++ ; else count_odd ++ ; } return min ( count_even , count_odd ) ; } int main ( ) { int arr [ ] = { 2 , 4 , 3 , 1 , 5 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << minCost ( arr , n ) ; return 0 ; }
Number of Subarrays with positive product | C ++ implementation of the approach ; Function to return the count of subarrays with negative product ; Replace current element with 1 if it is positive else replace it with - 1 instead ; Take product with previous element to form the prefix product ; Count positive and negative elements in the prefix product array ; Return the required count of subarrays ; Function to return the count of subarrays with positive product ; Total subarrays possible ; Count to subarrays with negative product ; Return the count of subarrays with positive product ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int negProdSubArr ( int arr [ ] , int n ) { int positive = 1 , negative = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( arr [ i ] > 0 ) arr [ i ] = 1 ; else arr [ i ] = -1 ; if ( i > 0 ) arr [ i ] *= arr [ i - 1 ] ; if ( arr [ i ] == 1 ) positive ++ ; else negative ++ ; } return ( positive * negative ) ; } int posProdSubArr ( int arr [ ] , int n ) { int total = ( n * ( n + 1 ) ) / 2 ; int cntNeg = negProdSubArr ( arr , n ) ; return ( total - cntNeg ) ; } int main ( ) { int arr [ ] = { 5 , -4 , -3 , 2 , -5 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << posProdSubArr ( arr , n ) ; return 0 ; }
Find the XOR of first N Prime Numbers | C ++ implementation of the approach ; Create a boolean array " prime [ 0 . . n ] " and initialize all entries it as true . A value in prime [ i ] will finally be false if i is Not a prime , else true . ; If prime [ p ] is not changed , then it is a prime ; Set all multiples of p to non - prime ; Function to return the xor of 1 st N prime numbers ; Count of prime numbers ; XOR of prime numbers ; If the number is prime xor it ; Increment the count ; Get to the next number ; Driver code ; Create the sieve ; Find the xor of 1 st n prime numbers
#include <bits/stdc++.h> NEW_LINE using namespace std ; #define MAX 10000 NEW_LINE bool prime [ MAX + 1 ] ; void SieveOfEratosthenes ( ) { memset ( prime , true , sizeof ( prime ) ) ; prime [ 1 ] = false ; for ( int p = 2 ; p * p <= MAX ; p ++ ) { if ( prime [ p ] == true ) { for ( int i = p * 2 ; i <= MAX ; i += p ) prime [ i ] = false ; } } } int xorFirstNPrime ( int n ) { int count = 0 , num = 1 ; int xorVal = 0 ; while ( count < n ) { if ( prime [ num ] ) { xorVal ^= num ; count ++ ; } num ++ ; } return xorVal ; } int main ( ) { SieveOfEratosthenes ( ) ; int n = 4 ; cout << xorFirstNPrime ( n ) ; return 0 ; }
Sum of all natural numbers from L to R ( for large values of L and R ) | C ++ implementation of the approach ; Value of inverse modulo 2 with 10 ^ 9 + 7 ; Function to return num % 1000000007 where num is a large number ; Initialize result ; One by one process all the digits of string ' num ' ; Function to return the sum of the integers from the given range modulo 1000000007 ; a stores the value of L modulo 10 ^ 9 + 7 ; b stores the value of R modulo 10 ^ 9 + 7 ; l stores the sum of natural numbers from 1 to ( a - 1 ) ; r stores the sum of natural numbers from 1 to b ; If the result is negative ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; #define mod 1000000007 NEW_LINE const long long inv2 = 500000004 ; long long int modulo ( string num ) { long long int res = 0 ; for ( long long int i = 0 ; i < num . length ( ) ; i ++ ) res = ( res * 10 + ( long long int ) num [ i ] - '0' ) % mod ; return res ; } long long int findSum ( string L , string R ) { long long int a , b , l , r , ret ; a = modulo ( L ) ; b = modulo ( R ) ; l = ( ( a * ( a - 1 ) ) % mod * inv2 ) % mod ; r = ( ( b * ( b + 1 ) ) % mod * inv2 ) % mod ; ret = ( r % mod - l % mod ) ; if ( ret < 0 ) ret = ret + mod ; else ret = ret % mod ; return ret ; } int main ( ) { string L = "88949273204" ; string R = "98429729474298592" ; cout << findSum ( L , R ) << endl ; return 0 ; }
Maximum subsequence sum such that all elements are K distance apart | C ++ implementation of the approach ; Function to return the maximum subarray sum for the array { a [ i ] , a [ i + k ] , a [ i + 2 k ] , ... } ; Function to return the sum of the maximum required subsequence ; To store the result ; Run a loop from 0 to k ; Find the maximum subarray sum for the array { a [ i ] , a [ i + k ] , a [ i + 2 k ] , ... } ; Return the maximum value ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int maxSubArraySum ( int a [ ] , int n , int k , int i ) { int max_so_far = INT_MIN , max_ending_here = 0 ; while ( i < n ) { max_ending_here = max_ending_here + a [ i ] ; if ( max_so_far < max_ending_here ) max_so_far = max_ending_here ; if ( max_ending_here < 0 ) max_ending_here = 0 ; i += k ; } return max_so_far ; } int find ( int arr [ ] , int n , int k ) { int maxSum = 0 ; for ( int i = 0 ; i <= min ( n , k ) ; i ++ ) { int sum = 0 ; maxSum = max ( maxSum , maxSubArraySum ( arr , n , k , i ) ) ; } return maxSum ; } int main ( ) { int arr [ ] = { 2 , -3 , -1 , -1 , 2 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; int k = 2 ; cout << find ( arr , n , k ) ; return 0 ; }
Generate N integers satisfying the given conditions | C ++ implementation of the approach ; Create a boolean array " prime [ 0 . . n ] " and initialize all entries it as true . A value in prime [ i ] will finally be false if i is Not a prime , else true . ; If prime [ p ] is not changed , then it is a prime ; Set all multiples of p to non - prime ; Function to find the first n odd prime numbers ; To store the current count of prime numbers ; Starting with 3 as 2 is an even prime number ; If i is prime ; Print i and increment count ; Driver code ; Create the sieve
#include <bits/stdc++.h> NEW_LINE using namespace std ; #define MAX 1000000 NEW_LINE bool prime [ MAX + 1 ] ; void SieveOfEratosthenes ( ) { memset ( prime , true , sizeof ( prime ) ) ; prime [ 1 ] = false ; for ( int p = 2 ; p * p <= MAX ; p ++ ) { if ( prime [ p ] == true ) { for ( int i = p * 2 ; i <= MAX ; i += p ) prime [ i ] = false ; } } } void solve ( int n ) { int count = 0 ; for ( int i = 3 ; count < n ; i ++ ) { if ( prime [ i ] ) { cout << i << " ▁ " ; count ++ ; } } } int main ( ) { SieveOfEratosthenes ( ) ; int n = 6 ; solve ( n ) ; return 0 ; }
Probability that a N digit number is palindrome | C ++ code of above approach ; Find the probability that a n digit number is palindrome ; Denominator ; Assign 10 ^ ( floor ( n / 2 ) ) to denominator ; Display the answer ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void solve ( int n ) { int n_2 = n / 2 ; string den ; den = "1" ; while ( n_2 -- ) den += '0' ; cout << 1 << " / " << den << " STRNEWLINE " ; } int main ( ) { int N = 5 ; solve ( N ) ; return 0 ; }
Ways to choose balls such that at least one ball is chosen | C ++ implementation of the approach ; Function to return the count of ways to choose the balls ; Calculate ( 2 ^ n ) % MOD ; Subtract the only where no ball was chosen ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; const int MOD = 1000000007 ; int countWays ( int n ) { int ans = 1 ; for ( int i = 0 ; i < n ; i ++ ) { ans *= 2 ; ans %= MOD ; } return ( ( ans - 1 + MOD ) % MOD ) ; } int main ( ) { int n = 3 ; cout << countWays ( n ) ; return 0 ; }
Minimize the sum of the array according the given condition | C ++ implementation ; Function to return the minimum sum ; sort the array to find the minimum element ; finding the number to divide ; Checking to what instance the sum has decreased ; getting the max difference ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void findMin ( int arr [ ] , int n ) { int sum = 0 ; for ( int i = 0 ; i < n ; i ++ ) sum += arr [ i ] ; sort ( arr , arr + n ) ; int min = arr [ 0 ] ; int max = 0 ; for ( int i = n - 1 ; i >= 1 ; i -- ) { int num = arr [ i ] ; int total = num + min ; int j ; for ( j = 2 ; j <= num ; j ++ ) { if ( num % j == 0 ) { int d = j ; int now = ( num / d ) + ( min * d ) ; int reduce = total - now ; if ( reduce > max ) max = reduce ; } } } cout << ( sum - max ) ; } int main ( ) { int arr [ ] = { 1 , 2 , 3 , 4 , 5 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; findMin ( arr , n ) ; }
Print all the permutation of length L using the elements of an array | Iterative | C ++ implementation ; Convert the number to Lth base and print the sequence ; Sequence is of length L ; Print the ith element of sequence ; Print all the permuataions ; There can be ( len ) ^ l permutations ; Convert i to len th base ; Driver code ; function call
#include <bits/stdc++.h> NEW_LINE using namespace std ; void convert_To_Len_th_base ( int n , int arr [ ] , int len , int L ) { for ( int i = 0 ; i < L ; i ++ ) { cout << arr [ n % len ] ; n /= len ; } cout << endl ; } void print ( int arr [ ] , int len , int L ) { for ( int i = 0 ; i < ( int ) pow ( len , L ) ; i ++ ) { convert_To_Len_th_base ( i , arr , len , L ) ; } } int main ( ) { int arr [ ] = { 1 , 2 , 3 } ; int len = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; int L = 2 ; print ( arr , len , L ) ; return 0 ; }
Number of possible permutations when absolute difference between number of elements to the right and left are given | C ++ implementation of the above approach ; Function to find the number of permutations possible of the original array to satisfy the given absolute differences ; To store the count of each a [ i ] in a map ; if n is odd ; check the count of each whether it satisfy the given criteria or not ; there is only 1 way for middle element . ; for others there are 2 ways . ; now find total ways ; When n is even . ; there will be no middle element so for each a [ i ] there will be 2 ways ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int totalways ( int * arr , int n ) { unordered_map < int , int > cnt ; for ( int i = 0 ; i < n ; ++ i ) { cnt [ arr [ i ] ] ++ ; } if ( n % 2 == 1 ) { int start = 0 , endd = n - 1 ; for ( int i = start ; i <= endd ; i = i + 2 ) { if ( i == 0 ) { if ( cnt [ i ] != 1 ) { return 0 ; } } else { if ( cnt [ i ] != 2 ) { return 0 ; } } } int ways = 1 ; start = 2 , endd = n - 1 ; for ( int i = start ; i <= endd ; i = i + 2 ) { ways = ways * 2 ; } return ways ; } else if ( n % 2 == 0 ) { int start = 1 , endd = n - 1 ; for ( int i = 1 ; i <= endd ; i = i + 2 ) { if ( cnt [ i ] != 2 ) return 0 ; } int ways = 1 ; for ( int i = start ; i <= endd ; i = i + 2 ) { ways = ways * 2 ; } return ways ; } } int main ( ) { int N = 5 ; int arr [ N ] = { 2 , 4 , 4 , 0 , 2 } ; cout << totalways ( arr , N ) ; return 0 ; }
Proizvolov 's Identity | CPP program to implement proizvolov 's identity ; Function to implement proizvolov 's identity ; According to proizvolov 's identity ; Driver code ; Function call
#include <bits/stdc++.h> NEW_LINE using namespace std ; int proizvolov ( int a [ ] , int b [ ] , int n ) { return n * n ; } int main ( ) { int a [ ] = { 1 , 5 , 6 , 8 , 10 } , b [ ] = { 9 , 7 , 4 , 3 , 2 } ; int n = sizeof ( a ) / sizeof ( a [ 0 ] ) ; cout << proizvolov ( a , b , n ) ; return 0 ; }
Find the ln ( X ) and log10X with the help of expansion | CPP code to Find the ln x and log < sub > 10 < / sub > x with the help of expansion ; Function to calculate ln x using expansion ; terminating value of the loop can be increased to improve the precision ; Function to calculate log10 x ; Driver Code ; setprecision ( 3 ) is used to display the output up to 3 decimal places
#include <cmath> NEW_LINE #include <iomanip> NEW_LINE #include <iostream> NEW_LINE using namespace std ; double calculateLnx ( double n ) { double num , mul , cal , sum = 0 ; num = ( n - 1 ) / ( n + 1 ) ; for ( int i = 1 ; i <= 1000 ; i ++ ) { mul = ( 2 * i ) - 1 ; cal = pow ( num , mul ) ; cal = cal / mul ; sum = sum + cal ; } sum = 2 * sum ; return sum ; } double calculateLogx ( double lnx ) { return ( lnx / 2.303 ) ; } int main ( ) { double lnx , logx , n = 5 ; lnx = calculateLnx ( n ) ; logx = calculateLogx ( lnx ) ; cout << fixed << setprecision ( 3 ) << " ln ▁ " << n << " ▁ = ▁ " << lnx << endl ; cout << fixed << setprecision ( 3 ) << " log10 ▁ " << n << " ▁ = ▁ " << logx << endl ; }
Find the sum of elements of the Matrix generated by the given rules | C ++ implementation of the approach ; Function to return the required sum ; To store the sum ; For every row ; Update the sum as A appears i number of times in the current row ; Update A for the next row ; Return the sum ; Driver code
#include <iostream> NEW_LINE using namespace std ; int sum ( int A , int B , int R ) { int sum = 0 ; for ( int i = 1 ; i <= R ; i ++ ) { sum = sum + ( i * A ) ; A = A + B ; } return sum ; } int main ( ) { int A = 5 , B = 3 , R = 3 ; cout << sum ( A , B , R ) ; return 0 ; }
Count total set bits in all numbers from 1 to n | Set 2 | C ++ implementation of the approach ; Function to return the sum of the count of set bits in the integers from 1 to n ; Ignore 0 as all the bits are unset ; To store the powers of 2 ; To store the result , it is initialized with n / 2 because the count of set least significant bits in the integers from 1 to n is n / 2 ; Loop for every bit required to represent n ; Total count of pairs of 0 s and 1 s ; totalPairs / 2 gives the complete count of the pairs of 1 s Multiplying it with the current power of 2 will give the count of 1 s in the current bit ; If the count of pairs was odd then add the remaining 1 s which could not be groupped together ; Next power of 2 ; Return the result ; Driver code
#include <iostream> NEW_LINE using namespace std ; int countSetBits ( int n ) { n ++ ; int powerOf2 = 2 ; int cnt = n / 2 ; while ( powerOf2 <= n ) { int totalPairs = n / powerOf2 ; cnt += ( totalPairs / 2 ) * powerOf2 ; cnt += ( totalPairs & 1 ) ? ( n % powerOf2 ) : 0 ; powerOf2 <<= 1 ; } return cnt ; } int main ( ) { int n = 14 ; cout << countSetBits ( n ) ; return 0 ; }
Find the height of a right | C ++ implementation of the approach ; Function to return the height of the right - angled triangle whose area is X times its base ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int getHeight ( int X ) { return ( 2 * X ) ; } int main ( ) { int X = 35 ; cout << getHeight ( X ) ; return 0 ; }
Find sum of inverse of the divisors when sum of divisors and the number is given | C ++ implementation of above approach ; Function to return the sum of inverse of divisors ; Calculating the answer ; Return the answer ; Driver code ; Function call
#include <bits/stdc++.h> NEW_LINE using namespace std ; double SumofInverseDivisors ( int N , int Sum ) { double ans = ( double ) ( Sum ) * 1.0 / ( double ) ( N ) ; return ans ; } int main ( ) { int N = 9 ; int Sum = 13 ; cout << setprecision ( 2 ) << fixed << SumofInverseDivisors ( N , Sum ) ; return 0 ; }
Number of triplets such that each value is less than N and each pair sum is a multiple of K | C ++ implementation of the above approach ; Function to return the number of triplets ; Initializing the count array ; Storing the frequency of each modulo class ; If K is odd ; If K is even ; Driver Code ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; int NoofTriplets ( int N , int K ) { int cnt [ K ] ; memset ( cnt , 0 , sizeof ( cnt ) ) ; for ( int i = 1 ; i <= N ; i += 1 ) { cnt [ i % K ] += 1 ; } if ( K & 1 ) return cnt [ 0 ] * cnt [ 0 ] * cnt [ 0 ] ; else { return ( cnt [ 0 ] * cnt [ 0 ] * cnt [ 0 ] + cnt [ K / 2 ] * cnt [ K / 2 ] * cnt [ K / 2 ] ) ; } } int main ( ) { int N = 3 , K = 2 ; cout << NoofTriplets ( N , K ) ; return 0 ; }
Find a number containing N | C ++ implementation of the approach ; Function to compute number using our deduced formula ; Initialize num to n - 1 ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; #define ll long long int NEW_LINE ll findNumber ( int n ) { ll num = n - 1 ; num = 2 * ( ll ) pow ( 4 , num ) ; num = floor ( num / 3.0 ) ; return num ; } int main ( ) { int n = 5 ; cout << findNumber ( n ) ; return 0 ; }
Find XOR of numbers from the range [ L , R ] | C ++ implementation of the approach ; Function to return the XOR of elements from the range [ 1 , n ] ; If n is a multiple of 4 ; If n % 4 gives remainder 1 ; If n % 4 gives remainder 2 ; If n % 4 gives remainder 3 ; Function to return the XOR of elements from the range [ l , r ] ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int findXOR ( int n ) { int mod = n % 4 ; if ( mod == 0 ) return n ; else if ( mod == 1 ) return 1 ; else if ( mod == 2 ) return n + 1 ; else if ( mod == 3 ) return 0 ; } int findXOR ( int l , int r ) { return ( findXOR ( l - 1 ) ^ findXOR ( r ) ) ; } int main ( ) { int l = 4 , r = 8 ; cout << findXOR ( l , r ) ; return 0 ; }
Number of elements from the array which are reachable after performing given operations on D | C ++ implementation of the approach ; Function to return the GCD of a and b ; Function to return the count of reachable integers from the given array ; GCD of A and B ; To store the count of reachable integers ; If current element can be reached ; Return the count ; 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 ) ; } int findReachable ( int arr [ ] , int D , int A , int B , int n ) { int gcd_AB = GCD ( A , B ) ; int count = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( ( arr [ i ] - D ) % gcd_AB == 0 ) count ++ ; } return count ; } int main ( ) { int arr [ ] = { 4 , 5 , 6 , 7 , 8 , 9 } ; int n = sizeof ( arr ) / sizeof ( int ) ; int D = 4 , A = 4 , B = 6 ; cout << findReachable ( arr , D , A , B , n ) ; return 0 ; }
Number of trees whose sum of degrees of all the vertices is L | C ++ implementation of the approach ; Iterative Function to calculate ( x ^ y ) in O ( log y ) ; Initialize result ; If y is odd , multiply x with result ; y must be even now y = y / 2 ; Function to return the count of required trees ; number of nodes ; Return the result ; Driver code
#include <iostream> NEW_LINE using namespace std ; #define ll long long int NEW_LINE ll power ( int x , ll y ) { ll res = 1 ; while ( y > 0 ) { if ( y & 1 ) res = ( res * x ) ; y = y >> 1 ; x = ( x * x ) ; } return res ; } ll solve ( int L ) { int n = L / 2 + 1 ; ll ans = power ( n , n - 2 ) ; return ans ; } int main ( ) { int L = 6 ; cout << solve ( L ) ; return 0 ; }
Change one element in the given array to make it an Arithmetic Progression | C ++ program to change one element of an array such that the resulting array is in arithmetic progression . ; Finds the initial term and common difference and prints the resulting sequence . ; Check if the first three elements are in arithmetic progression ; Check if the first element is not in arithmetic progression ; The first and fourth element are in arithmetic progression ; Print the arithmetic progression ; Driver Program
#include <bits/stdc++.h> NEW_LINE using namespace std ; void makeAP ( int arr [ ] , int n ) { int initial_term , common_difference ; if ( n == 3 ) { common_difference = arr [ 2 ] - arr [ 1 ] ; initial_term = arr [ 1 ] - common_difference ; } else if ( ( arr [ 1 ] - arr [ 0 ] ) == arr [ 2 ] - arr [ 1 ] ) { initial_term = arr [ 0 ] ; common_difference = arr [ 1 ] - arr [ 0 ] ; } else if ( ( arr [ 2 ] - arr [ 1 ] ) == ( arr [ 3 ] - arr [ 2 ] ) ) { common_difference = arr [ 2 ] - arr [ 1 ] ; initial_term = arr [ 1 ] - common_difference ; } else { common_difference = ( arr [ 3 ] - arr [ 0 ] ) / 3 ; initial_term = arr [ 0 ] ; } for ( int i = 0 ; i < n ; i ++ ) cout << initial_term + ( i * common_difference ) << " ▁ " ; cout << endl ; } int main ( ) { int arr [ ] = { 1 , 3 , 7 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; makeAP ( arr , n ) ; return 0 ; }
Find if nCr is divisible by the given prime | C ++ implementation of the approach ; Function to return the highest power of p that divides n ! implementing Legendre Formula ; Return the highest power of p which divides n ! ; Function that returns true if nCr is divisible by p ; Find the highest powers of p that divide n ! , r ! and ( n - r ) ! ; If nCr is divisible by p ; Driver code
#include <bits/stdc++.h> NEW_LINE #define ll long long int NEW_LINE using namespace std ; int getfactor ( int n , int p ) { int pw = 0 ; while ( n ) { n /= p ; pw += n ; } return pw ; } bool isDivisible ( int n , int r , int p ) { int x1 = getfactor ( n , p ) ; int x2 = getfactor ( r , p ) ; int x3 = getfactor ( n - r , p ) ; if ( x1 > x2 + x3 ) return true ; return false ; } int main ( ) { int n = 7 , r = 2 , p = 7 ; if ( isDivisible ( n , r , p ) ) cout << " Yes " ; else cout << " No " ; return 0 ; }
Check if the number is even or odd whose digits and base ( radix ) is given | C ++ implementation of the approach ; Function that returns true if the number represented by arr [ ] is even in base r ; If the base is even , then the last digit is checked ; If base is odd , then the number of odd digits are checked ; To store the count of odd digits ; Number is odd ; Driver code
#include <iostream> NEW_LINE using namespace std ; bool isEven ( int arr [ ] , int n , int r ) { if ( r % 2 == 0 ) { if ( arr [ n - 1 ] % 2 == 0 ) return true ; } else { int oddCount = 0 ; for ( int i = 0 ; i < n ; ++ i ) { if ( arr [ i ] % 2 != 0 ) oddCount ++ ; } if ( oddCount % 2 == 0 ) return true ; } return false ; } int main ( ) { int arr [ ] = { 1 , 0 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; int r = 2 ; if ( isEven ( arr , n , r ) ) cout << " Even " ; else cout << " Odd " ; return 0 ; }
Bitwise AND of sub | C ++ implementation of the approach ; Function to return the minimum possible value of | K - X | where X is the bitwise AND of the elements of some sub - array ; Check all possible sub - arrays ; Find the overall minimum ; No need to perform more AND operations as | k - X | will increase ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int closetAND ( int arr [ ] , int n , int k ) { int ans = INT_MAX ; for ( int i = 0 ; i < n ; i ++ ) { int X = arr [ i ] ; for ( int j = i ; j < n ; j ++ ) { X &= arr [ j ] ; ans = min ( ans , abs ( k - X ) ) ; if ( X <= k ) break ; } } return ans ; } int main ( ) { int arr [ ] = { 4 , 7 , 10 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; int k = 2 ; cout << closetAND ( arr , n , k ) ; return 0 ; }
Count of quadruplets from range [ L , R ] having GCD equal to K | C ++ implementation of the approach ; Function to return the gcd of a and b ; Function to return the count of quadruplets having gcd = k ; Count the frequency of every possible gcd value in the range ; To store the required count ; Calculate the answer using frequency values ; Return the required count ; Driver code
#include <iostream> NEW_LINE using namespace std ; int gcd ( int a , int b ) { if ( b == 0 ) return a ; return gcd ( b , a % b ) ; } int countQuadruplets ( int l , int r , int k ) { int frequency [ r + 1 ] = { 0 } ; for ( int i = l ; i <= r ; i ++ ) { for ( int j = l ; j <= r ; j ++ ) { frequency [ gcd ( i , j ) ] ++ ; } } long long answer = 0 ; for ( int i = 1 ; i <= r ; i ++ ) { for ( int j = 1 ; j <= r ; j ++ ) { if ( gcd ( i , j ) == k ) { answer += ( frequency [ i ] * frequency [ j ] ) ; } } } return answer ; } int main ( ) { int l = 1 , r = 10 , k = 2 ; cout << countQuadruplets ( l , r , k ) ; return 0 ; }
Rearrange the array to maximize the number of primes in prefix sum of the array | C ++ implementation of the approach ; Function to print the re - arranged array ; Count the number of ones and twos in a [ ] ; If the array element is 1 ; Array element is 2 ; If it has at least one 2 Fill up first 2 ; Decrease the cnt of ones if even ; Fill up with odd count of ones ; Fill up with remaining twos ; If even ones , then fill last position ; Print the rearranged array ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void solve ( int a [ ] , int n ) { int ones = 0 , twos = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( a [ i ] == 1 ) ones ++ ; else twos ++ ; } int ind = 0 ; if ( twos ) a [ ind ++ ] = 2 ; bool evenOnes = ( ones % 2 == 0 ) ? true : false ; if ( evenOnes ) ones -= 1 ; for ( int i = 0 ; i < ones ; i ++ ) a [ ind ++ ] = 1 ; for ( int i = 0 ; i < twos - 1 ; i ++ ) a [ ind ++ ] = 2 ; if ( evenOnes ) a [ ind ++ ] = 1 ; for ( int i = 0 ; i < n ; i ++ ) cout << a [ i ] << " ▁ " ; } int main ( ) { int a [ ] = { 1 , 2 , 1 , 2 , 1 } ; int n = sizeof ( a ) / sizeof ( a [ 0 ] ) ; solve ( a , n ) ; return 0 ; }
Generate an Array in which count of even and odd sum sub | C ++ implementation of the approach ; Function to generate and print the required array ; Find the number of odd prefix sums ; If no odd prefix sum found ; Calculating the number of even prefix sums ; Stores the current prefix sum ; If current prefix sum is even ; Print 0 until e = EvenPreSums - 1 ; Print 1 when e = EvenPreSums ; Print 0 for rest of the values ; Driver code
#include <algorithm> NEW_LINE #include <iostream> NEW_LINE using namespace std ; void CreateArray ( int N , int even , int odd ) { int temp = -1 ; int OddPreSums ; for ( int i = 0 ; i <= N + 1 ; i ++ ) { if ( i * ( ( N + 1 ) - i ) == odd ) { temp = 0 ; OddPreSums = i ; break ; } } if ( temp == -1 ) { cout << temp << endl ; } else { int EvenPreSums = ( N + 1 ) - OddPreSums ; int e = 1 ; int o = 0 ; int CurrSum = 0 ; for ( int i = 0 ; i < N ; i ++ ) { if ( CurrSum % 2 == 0 ) { if ( e < EvenPreSums ) { e ++ ; cout << "0 ▁ " ; } else { o ++ ; cout << "1 ▁ " ; CurrSum ++ ; } } else { if ( e < EvenPreSums ) { e ++ ; cout << "1 ▁ " ; CurrSum ++ ; } else { o ++ ; cout << "0 ▁ " ; } } } cout << endl ; } } int main ( ) { int N = 15 ; int even = 60 , odd = 60 ; CreateArray ( N , even , odd ) ; return 0 ; }
Minimum operations required to change the array such that | arr [ i ] | C ++ implementation of the approach ; Function to return the minimum number of operations required ; Minimum and maximum elements from the array ; To store the minimum number of operations required ; To store the number of operations required to change every element to either ( num - 1 ) , num or ( num + 1 ) ; If current element is not already num ; Add the count of operations required to change arr [ i ] ; Update the minimum operations so far ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int changeTheArray ( int arr [ ] , int n ) { int minEle = * ( std :: min_element ( arr , arr + n ) ) ; int maxEle = * ( std :: max_element ( arr , arr + n ) ) ; int minOperations = INT_MAX ; for ( int num = minEle ; num <= maxEle ; num ++ ) { int operations = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( arr [ i ] != num ) { operations += ( abs ( num - arr [ i ] ) - 1 ) ; } } minOperations = min ( minOperations , operations ) ; } return minOperations ; } int main ( ) { int arr [ ] = { 10 , 1 , 4 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << changeTheArray ( arr , n ) ; return 0 ; }
Choose X such that ( A xor X ) + ( B xor X ) is minimized | C ++ implementation of the approach ; Function to return the integer X such that ( A xor X ) + ( B ^ X ) is minimized ; While either A or B is non - zero ; Position at which both A and B have a set bit ; Inserting a set bit in x ; Right shifting both numbers to traverse all the bits ; Driver code
#include <iostream> NEW_LINE using namespace std ; int findX ( int A , int B ) { int j = 0 , x = 0 ; while ( A B ) { if ( ( A & 1 ) && ( B & 1 ) ) { x += ( 1 << j ) ; } A >>= 1 ; B >>= 1 ; j += 1 ; } return x ; } int main ( ) { int A = 2 , B = 3 ; int X = findX ( A , B ) ; cout << " X ▁ = ▁ " << X << " , ▁ Sum ▁ = ▁ " << ( A ^ X ) + ( B ^ X ) ; return 0 ; }
Choose X such that ( A xor X ) + ( B xor X ) is minimized | c ++ implementation of above approach ; finding X ; finding Sum ; Driver code
#include <iostream> NEW_LINE using namespace std ; int findX ( int A , int B ) { return A & B ; } int findSum ( int A , int B ) { return A ^ B ; } int main ( ) { int A = 2 , B = 3 ; cout << " X ▁ = ▁ " << findX ( A , B ) << " , ▁ Sum ▁ = ▁ " << findSum ( A , B ) ; return 0 ; }
Compare sum of first N | C ++ implementation of the approach ; Function that returns true if sum of first n - 1 elements of the array is equal to the last element ; Find the sum of first n - 1 elements of the array ; If sum equals to the last element ; Driver code
#include <iostream> NEW_LINE using namespace std ; bool isSumEqual ( int ar [ ] , int n ) { int sum = 0 ; for ( int i = 0 ; i < n - 1 ; i ++ ) sum += ar [ i ] ; if ( sum == ar [ n - 1 ] ) return true ; return false ; } int main ( ) { int arr [ ] = { 1 , 2 , 3 , 4 , 10 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; if ( isSumEqual ( arr , n ) ) cout << " Yes " ; else cout << " No " ; return 0 ; }
Count number of 1 s in the array after N moves | C ++ implementation of the above approach ; Function to count number of perfect squares ; Counting number of perfect squares between a and b ; Function to count number of 1 s in array after N moves ; Driver Code ; Initialize array size ; Initialize all elements to 0
#include <bits/stdc++.h> NEW_LINE using namespace std ; int perfectSquares ( int a , int b ) { return ( floor ( sqrt ( b ) ) - ceil ( sqrt ( a ) ) + 1 ) ; } int countOnes ( int arr [ ] , int n ) { return perfectSquares ( 1 , n ) ; } int main ( ) { int N = 10 ; int arr [ 10 ] = { 0 } ; cout << countOnes ( arr , N ) ; return 0 ; }
Find the position of box which occupies the given ball | C ++ implementation of the approach ; Function to print the position of each boxes where a ball has to be placed ; Find the cumulative sum of array A [ ] ; Find the position of box for each ball ; Row number ; Column ( position of box in particular row ) ; Row + 1 denotes row if indexing of array start from 1 ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void printPosition ( int A [ ] , int B [ ] , int sizeOfA , int sizeOfB ) { for ( int i = 1 ; i < sizeOfA ; i ++ ) A [ i ] += A [ i - 1 ] ; for ( int i = 0 ; i < sizeOfB ; i ++ ) { int row = lower_bound ( A , A + sizeOfA , B [ i ] ) - A ; int boxNumber = ( row >= 1 ) ? B [ i ] - A [ row - 1 ] : B [ i ] ; cout << row + 1 << " , ▁ " << boxNumber << " STRNEWLINE " ; } } int main ( ) { int A [ ] = { 2 , 2 , 2 , 2 } ; int B [ ] = { 1 , 2 , 3 , 4 } ; int sizeOfA = sizeof ( A ) / sizeof ( A [ 0 ] ) ; int sizeOfB = sizeof ( B ) / sizeof ( B [ 0 ] ) ; printPosition ( A , B , sizeOfA , sizeOfB ) ; return 0 ; }
Highest power of a number that divides other number | C ++ program to implement the above approach ; Function to get the prime factors and its count of times it divides ; Count the number of 2 s that divide n ; n must be odd at this point . So we can skip one element ( Note i = i + 2 ) ; While i divides n , count i and divide n ; This condition is to handle the case when n is a prime number greater than 2 ; Function to return the highest power ; Initialize two arrays ; Get the prime factors of n and m ; Iterate and find the maximum power ; If i not a prime factor of n and m ; If i is a prime factor of n and m If count of i dividing m is more than i dividing n , then power will be 0 ; If i is a prime factor of M ; get the maximum power ; Drivers code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void primeFactors ( int n , int freq [ ] ) { int cnt = 0 ; while ( n % 2 == 0 ) { cnt ++ ; n = n / 2 ; } freq [ 2 ] = cnt ; for ( int i = 3 ; i <= sqrt ( n ) ; i = i + 2 ) { cnt = 0 ; while ( n % i == 0 ) { cnt ++ ; n = n / i ; } freq [ i ] = cnt ; } if ( n > 2 ) freq [ n ] = 1 ; } int getMaximumPower ( int n , int m ) { int freq1 [ n + 1 ] , freq2 [ m + 1 ] ; memset ( freq1 , 0 , sizeof freq1 ) ; memset ( freq2 , 0 , sizeof freq2 ) ; primeFactors ( n , freq1 ) ; primeFactors ( m , freq2 ) ; int maxi = 0 ; for ( int i = 2 ; i <= m ; i ++ ) { if ( freq1 [ i ] == 0 && freq2 [ i ] == 0 ) continue ; if ( freq2 [ i ] > freq1 [ i ] ) return 0 ; if ( freq2 [ i ] ) { maxi = max ( maxi , freq1 [ i ] / freq2 [ i ] ) ; } } return maxi ; } int main ( ) { int n = 48 , m = 4 ; cout << getMaximumPower ( n , m ) ; return 0 ; }
Find the number of divisors of all numbers in the range [ 1 , n ] | C ++ implementation of the approach ; Function to find the number of divisors of all numbers in the range [ 1 , n ] ; Array to store the count of divisors ; For every number from 1 to n ; Increase divisors count for every number divisible by i ; Print the divisors ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void findDivisors ( int n ) { int div [ n + 1 ] ; memset ( div , 0 , sizeof div ) ; for ( int i = 1 ; i <= n ; i ++ ) { for ( int j = 1 ; j * i <= n ; j ++ ) div [ i * j ] ++ ; } for ( int i = 1 ; i <= n ; i ++ ) cout << div [ i ] << " ▁ " ; } int main ( ) { int n = 10 ; findDivisors ( n ) ; return 0 ; }
Predict the winner of the game on the basis of absolute difference of sum by selecting numbers | C ++ implementation of the approach ; Function to decide the winner ; Iterate for all numbers in the array ; If mod gives 0 ; If mod gives 1 ; If mod gives 2 ; If mod gives 3 ; Check the winning condition for X ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int decideWinner ( int a [ ] , int n ) { int count0 = 0 ; int count1 = 0 ; int count2 = 0 ; int count3 = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( a [ i ] % 4 == 0 ) count0 ++ ; else if ( a [ i ] % 4 == 1 ) count1 ++ ; else if ( a [ i ] % 4 == 2 ) count2 ++ ; else if ( a [ i ] % 4 == 3 ) count3 ++ ; } if ( count0 % 2 == 0 && count1 % 2 == 0 && count2 % 2 == 0 && count3 == 0 ) return 1 ; else return 2 ; } int main ( ) { int a [ ] = { 4 , 8 , 5 , 9 } ; int n = sizeof ( a ) / sizeof ( a [ 0 ] ) ; if ( decideWinner ( a , n ) == 1 ) cout << " X ▁ wins " ; else cout << " Y ▁ wins " ; return 0 ; }
Count all prefixes of the given binary array which are divisible by x | C ++ implementation of the approach ; Function to return the count of total binary prefix which are divisible by x ; Initialize with zero ; Instead of converting all prefixes to decimal , take reminder with x ; If number is divisible by x then reminder = 0 ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int CntDivbyX ( int arr [ ] , int n , int x ) { int number = 0 ; int count = 0 ; for ( int i = 0 ; i < n ; i ++ ) { number = ( number * 2 + arr [ i ] ) % x ; if ( number == 0 ) count += 1 ; } return count ; } int main ( ) { int arr [ ] = { 1 , 0 , 1 , 0 , 1 , 1 , 0 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; int x = 2 ; cout << CntDivbyX ( arr , n , x ) ; return 0 ; }
Length of the smallest number which is divisible by K and formed by using 1 's only | C ++ implementation of the approach ; Function to return length of the resultant number ; If K is a multiple of 2 or 5 ; Instead of generating all possible numbers 1 , 11 , 111 , 111 , ... , K 1 's Take remainder with K ; If number is divisible by k then remainder will be 0 ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int numLen ( int K ) { if ( K % 2 == 0 K % 5 == 0 ) return -1 ; int number = 0 ; int len = 1 ; for ( len = 1 ; len <= K ; len ++ ) { number = ( number * 10 + 1 ) % K ; if ( number == 0 ) return len ; } return -1 ; } int main ( ) { int K = 7 ; cout << numLen ( K ) ; return 0 ; }
Sum of multiplication of triplet of divisors of a number | C ++ implementation of the approach ; Global array declaration ; Function to find the sum of multiplication of every triplet in the divisors of a number ; sum1 [ x ] represents the sum of all the divisors of x ; Adding i to sum1 [ j ] because i is a divisor of j ; sum2 [ x ] represents the sum of all the divisors of x ; Here i is divisor of j and sum1 [ j ] - i represents sum of all divisors of j which do not include i so we add i * ( sum1 [ j ] - i ) to sum2 [ j ] ; In the above implementation we have considered every pair two times so we have to divide every sum2 array element by 2 ; Here i is the divisor of j and we are trying to add the sum of multiplication of all triplets of divisors of j such that one of the divisors is i ; In the above implementation we have considered every triplet three times so we have to divide every sum3 array element by 3 ; Print the results ; Driver code ; Precomputing
#include <bits/stdc++.h> NEW_LINE using namespace std ; #define ll long long NEW_LINE const ll max_Element = 1e6 + 5 ; int sum1 [ max_Element ] , sum2 [ max_Element ] , sum3 [ max_Element ] ; void precomputation ( int arr [ ] , int n ) { for ( int i = 1 ; i < max_Element ; i ++ ) for ( int j = i ; j < max_Element ; j += i ) sum1 [ j ] += i ; for ( int i = 1 ; i < max_Element ; i ++ ) for ( int j = i ; j < max_Element ; j += i ) sum2 [ j ] += ( sum1 [ j ] - i ) * i ; for ( int i = 1 ; i < max_Element ; i ++ ) sum2 [ i ] /= 2 ; for ( int i = 1 ; i < max_Element ; i ++ ) for ( int j = i ; j < max_Element ; j += i ) sum3 [ j ] += i * ( sum2 [ j ] - i * ( sum1 [ j ] - i ) ) ; for ( int i = 1 ; i < max_Element ; i ++ ) sum3 [ i ] /= 3 ; for ( int i = 0 ; i < n ; i ++ ) cout << sum3 [ arr [ i ] ] << " ▁ " ; } int main ( ) { int arr [ ] = { 9 , 5 , 6 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; precomputation ( arr , n ) ; return 0 ; }
Sum of Fibonacci Numbers in a range | C ++ implementation of the approach ; Function to return the nth Fibonacci number ; Function to return the required sum ; Using our deduced result ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int fib ( int n ) { double phi = ( 1 + sqrt ( 5 ) ) / 2 ; return round ( pow ( phi , n ) / sqrt ( 5 ) ) ; } int calculateSum ( int l , int r ) { int sum = fib ( r + 2 ) - fib ( l + 1 ) ; return sum ; } int main ( ) { int l = 4 , r = 8 ; cout << calculateSum ( l , r ) ; return 0 ; }