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 sati...
#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 - ...
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 n...
#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 ) ;...
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...
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...
#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 ==...
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 en...
#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 ( ) { b...
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...
#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 ( bitwis...
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...
#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 ;...
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 ne...
#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 ) ...
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 ▁ ...
#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 ( ) , '...
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 ;...
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 ...
#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 ) ...
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 ...
#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 largest...
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 [ ] =...
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...
#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 ( s...
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 great...
#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 ;...
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 ; } e...
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 ...
#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 ++ ;...
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 c...
#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 ...
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 - st...
#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 )...
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 [...
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...
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 ...
#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 = N...
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 ; ...
#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 ) r...
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 . ; ...
#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...
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 ...
#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 ) ...
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...
#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 [...
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 operat...
#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 ; i...
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 fa...
#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 << " ] "...
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...
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 ...
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 ...
#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...
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 numb...
#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 ) r...
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...
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 = 9...
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 ( ) { in...
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 la...
#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 ) r...
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...
#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 ; } doubl...
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 ...
#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 ( ) ...
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 thei...
#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 ( ) ...
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 ...
#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...
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 fi...
#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 ma...
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 i...
#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 << fi...
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 ...
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 angl...
#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 ...
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 ) ) ...
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 <...
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 mai...
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 ( )...
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 ...
#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...
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 negat...
#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 ...
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 ...
#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 ) ...
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 su...
#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 ; ...
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...
#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 ...
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 m...
#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 ...
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 ...
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 ; D...
#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 ++ )...
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...
#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 ] !=...
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 ; setprecisio...
#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 ...
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 le...
#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 ( ) {...
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 ...
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 [ ...
#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 ( )...
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 el...
#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 ==...
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 ; Re...
#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 ...
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 arithmeti...
#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 ...
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 ...
#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...
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 s...
#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 ...
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 c...
#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 ( )...
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 u...
#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 ) ] ++ ;...
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...
#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...
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 eve...
#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 << en...
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 ch...
#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 ; ...
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 t...
#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 ▁ = ▁ " ...
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 ] ) ;...
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 ) ; re...
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 + ...
#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...
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...
#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 ) ...
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 ...
#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...
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 cod...
#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 ++ ; el...
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 remi...
#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 , ...
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 i...
#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 ) ...
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 ...
#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 ...
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 , ...