Datasets:
text
stringlengths 17
4.49k
| code
stringlengths 49
5.46k
|
---|---|
Maximum Prefix Sum possible by merging two given arrays | C ++ Program to implement the above approach ; Stores the maximum prefix sum of the array A [ ] ; Traverse the array A [ ] ; Stores the maximum prefix sum of the array B [ ] ; Traverse the array B [ ] ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int maxPresum ( vector < int > a , vector < int > b ) { int X = max ( a [ 0 ] , 0 ) ; for ( int i = 1 ; i < a . size ( ) ; i ++ ) { a [ i ] += a [ i - 1 ] ; X = max ( X , a [ i ] ) ; } int Y = max ( b [ 0 ] , 0 ) ; for ( int i = 1 ; i < b . size ( ) ; i ++ ) { b [ i ] += b [ i - 1 ] ; Y = max ( Y , b [ i ] ) ; } return X + Y ; } int main ( ) { vector < int > A = { 2 , -1 , 4 , -5 } ; vector < int > B = { 4 , -3 , 12 , 4 , -3 } ; cout << maxPresum ( A , B ) << endl ; } |
Check if a number can be represented as sum of two positive perfect cubes | C ++ program for the above approach ; Function to check if N can be represented as sum of two perfect cubes or not ; if it is same return true ; ; if the curr smaller than n increment the lo ; if the curr is greater than curr decrement the hi ; Driver Code ; Function call to check if N can be represented as sum of two perfect cubes or not | #include <bits/stdc++.h> NEW_LINE using namespace std ; bool sumOfTwoCubes ( int n ) { long long int lo = 1 , hi = ( long long int ) cbrt ( n ) ; while ( lo <= hi ) { long long int curr = ( lo * lo * lo + hi * hi * hi ) ; if ( curr == n ) return true ; if ( curr < n ) lo ++ ; else hi -- ; } return false ; } int main ( ) { int N = 28 ; if ( sumOfTwoCubes ( N ) ) { cout << " True " ; } else { cout << " False " ; } return 0 ; } |
Generate an N | C ++ program for the above approach ; Function to generate all prime numbers upto 10 ^ 6 ; Initialize sieve [ ] as 1 ; Iterate over the range [ 2 , N ] ; If current element is non - prime ; Make all multiples of i as 0 ; Function to construct an array A [ ] satisfying the given conditions ; Stores the resultant array ; Stores all prime numbers ; Sieve of Erastosthenes ; Append the integer i if it is a prime ; Indicates current position in list of prime numbers ; Traverse the array arr [ ] ; If already filled with another prime number ; If A [ i ] is not filled but A [ ind ] is filled ; Store A [ i ] = A [ ind ] ; If none of them were filled ; To make sure A [ i ] does not affect other values , store next prime number ; Print the resultant array ; Driver Code ; Function Call | #include <bits/stdc++.h> NEW_LINE using namespace std ; int sieve [ 1000000 ] ; void sieveOfPrimes ( ) { memset ( sieve , 1 , sizeof ( sieve ) ) ; int N = 1000000 ; for ( int i = 2 ; i * i <= N ; i ++ ) { if ( sieve [ i ] == 0 ) continue ; for ( int j = i * i ; j <= N ; j += i ) sieve [ j ] = 0 ; } } void getArray ( int * arr , int N ) { int A [ N ] = { 0 } ; vector < int > v ; sieveOfPrimes ( ) ; for ( int i = 2 ; i <= 1e5 ; i ++ ) if ( sieve [ i ] ) v . push_back ( i ) ; int j = 0 ; for ( int i = 0 ; i < N ; i ++ ) { int ind = arr [ i ] ; if ( A [ i ] != 0 ) continue ; else if ( A [ ind ] != 0 ) A [ i ] = A [ ind ] ; else { int prime = v [ j ++ ] ; A [ i ] = prime ; A [ ind ] = A [ i ] ; } } for ( int i = 0 ; i < N ; i ++ ) { cout << A [ i ] << " β " ; } } int main ( ) { int arr [ ] = { 4 , 1 , 2 , 3 , 4 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; getArray ( arr , N ) ; return 0 ; } |
Nth natural number after removing all numbers consisting of the digit 9 | C ++ implementation of above approach ; Function to find Nth number in base 9 ; Stores the Nth number ; Iterate while N is greater than 0 ; Update result ; Divide N by 9 ; Multiply p by 10 ; Return result ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; long long findNthNumber ( long long N ) { long long result = 0 ; long long p = 1 ; while ( N > 0 ) { result += ( p * ( N % 9 ) ) ; N = N / 9 ; p = p * 10 ; } return result ; } int main ( ) { int N = 9 ; cout << findNthNumber ( N ) ; return 0 ; } |
Check if an integer is rotation of another given integer | C ++ implementation of the approach ; Function to check if the integer A is a rotation of the integer B ; Stores the count of digits in A ; Stores the count of digits in B ; If dig1 not equal to dig2 ; Stores position of first digit ; Stores the first digit ; Rotate the digits of the integer ; If A is equal to B ; If A is equal to the initial value of integer A ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int check ( int A , int B ) { if ( A == B ) { return 1 ; } int dig1 = floor ( log10 ( A ) + 1 ) ; int dig2 = floor ( log10 ( B ) + 1 ) ; if ( dig1 != dig2 ) { return 0 ; } int temp = A ; while ( 1 ) { int power = pow ( 10 , dig1 - 1 ) ; int firstdigit = A / power ; A = A - firstdigit * power ; A = A * 10 + firstdigit ; if ( A == B ) { return 1 ; } if ( A == temp ) { return 0 ; } } } int main ( ) { int A = 967 , B = 679 ; if ( check ( A , B ) ) cout << " Yes " ; else cout << " No " << endl ; return 0 ; } |
Count of quadruples with product of a pair equal to the product of the remaining pair | C ++ program for the above approach ; Function to count the number of unique quadruples from an array that satisfies the given condition ; Hashmap to store the product of pairs ; Store the count of required quadruples ; Traverse the array arr [ ] and generate all possible pairs ; Store their product ; Pair ( a , b ) can be used to generate 8 unique permutations with another pair ( c , d ) ; Increment um [ prod ] by 1 ; Print the result ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; void sameProductQuadruples ( int nums [ ] , int N ) { unordered_map < int , int > umap ; int res = 0 ; for ( int i = 0 ; i < N ; ++ i ) { for ( int j = i + 1 ; j < N ; ++ j ) { int prod = nums [ i ] * nums [ j ] ; res += 8 * umap [ prod ] ; ++ umap [ prod ] ; } } cout << res ; } int main ( ) { int arr [ ] = { 2 , 3 , 4 , 6 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; sameProductQuadruples ( arr , N ) ; return 0 ; } |
Count ways to place M objects in distinct partitions of N boxes | C ++ implementation of the above Approach ; Iterative Function to calculate ( x ^ y ) % p in O ( log y ) ; Initialize Result ; Update x if x >= MOD to avoid multiplication overflow ; If y is odd , multiply x with result ; y = y / 2 ; Change x to x ^ 2 ; Utility function to find the Total Number of Ways ; Number of Even Indexed Boxes ; Number of partitions of Even Indexed Boxes ; Number of ways to distribute objects ; Driver Code ; N = number of boxes M = number of distinct objects ; Function call to get Total Number of Ways | #include <bits/stdc++.h> NEW_LINE using namespace std ; const int MOD = 1000000007 ; int power ( int x , unsigned int y , int p = MOD ) { int res = 1 ; x = x % p ; while ( y > 0 ) { if ( y & 1 ) res = ( res * 1LL * x ) % p ; y = y >> 1 ; x = ( x * 1LL * x ) % p ; } return res ; } void totalWays ( int N , int M ) { int X = N / 2 ; int S = ( X * 1LL * ( X + 1 ) ) % MOD ; cout << power ( S , M , MOD ) << " STRNEWLINE " ; } int main ( ) { int N = 5 , M = 2 ; totalWays ( N , M ) ; return 0 ; } |
Check if a graph constructed from an array based on given conditions consists of a cycle or not | C ++ program for the above approach ; Function to check if the graph constructed from given array contains a cycle or not ; Traverse the array ; If arr [ i ] is less than arr [ i - 1 ] and arr [ i ] ; Driver Code ; Given array ; Size of the array | #include <bits/stdc++.h> NEW_LINE using namespace std ; void isCycleExists ( int arr [ ] , int N ) { bool valley = 0 ; for ( int i = 1 ; i < N ; i ++ ) { if ( arr [ i ] < arr [ i - 1 ] && arr [ i ] < arr [ i + 1 ] ) { cout << " Yes " << endl ; return ; } } cout << " No " ; } int main ( ) { int arr [ ] = { 1 , 3 , 2 , 4 , 5 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; isCycleExists ( arr , N ) ; return 0 ; } |
Maximize first array element by performing given operations at most K times | C ++ program for the above approach ; Function to maximize the first array element ; Traverse the array ; Initialize cur_val to a [ i ] ; If all operations are not over yet ; If current value is greater than zero ; Incrementing first element of array by 1 ; Decrementing current value of array by 1 ; Decrementing number of operations by i ; If current value is zero , then break ; Print first array element ; Driver Code ; Given array ; Size of the array ; Given K ; Prints the maximum possible value of the first array element | #include <bits/stdc++.h> NEW_LINE using namespace std ; int getMax ( int arr [ ] , int N , int K ) { for ( int i = 1 ; i < N ; i ++ ) { int cur_val = arr [ i ] ; while ( K >= i ) { if ( cur_val > 0 ) { arr [ 0 ] = arr [ 0 ] + 1 ; cur_val = cur_val - 1 ; K = K - i ; } else break ; } } cout << arr [ 0 ] ; } int main ( ) { int arr [ ] = { 1 , 0 , 3 , 2 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; int K = 5 ; getMax ( arr , N , K ) ; return 0 ; } |
Count Non | C ++ program of the above approach ; Function to find the gcd of the two numbers ; Function to find distinct elements in the array by repeatidely inserting the absolute difference of all possible pairs ; Stores largest element of the array ; Traverse the array , arr [ ] ; Update max_value ; Stores GCD of array ; Traverse the array , arr [ ] ; Update GCDArr ; Stores distinct elements in the array by repeatidely inserting absolute difference of all possible pairs ; Driver Code ; Given array arr [ ] | #include <bits/stdc++.h> NEW_LINE using namespace std ; int gcd ( int a , int b ) { if ( a == 0 ) return b ; return gcd ( b % a , a ) ; } int DistinctValues ( int arr [ ] , int N ) { int max_value = INT_MIN ; for ( int i = 0 ; i < N ; ++ i ) { max_value = max ( max_value , arr [ i ] ) ; } int GCDArr = arr [ 0 ] ; for ( int i = 1 ; i < N ; ++ i ) { GCDArr = gcd ( GCDArr , arr [ i ] ) ; } int answer = ( max_value / GCDArr ) + 1 ; return answer ; } int main ( ) { int arr [ ] = { 4 , 12 , 16 , 24 } ; int N = sizeof ( arr ) / sizeof ( int ) ; cout << DistinctValues ( arr , N ) ; return 0 ; } |
Minimum row or column swaps required to make every pair of adjacent cell of a Binary Matrix distinct | C ++ program for the above approach ; Function to return number of moves to convert matrix into chessboard ; Size of the matrix ; Traverse the matrix ; Initialize rowSum to count 1 s in row ; Initialize colSum to count 1 s in column ; To store no . of rows to be corrected ; To store no . of columns to be corrected ; Traverse in the range [ 0 , N - 1 ] ; Check if rows is either N / 2 or ( N + 1 ) / 2 and return - 1 ; Check if rows is either N / 2 or ( N + 1 ) / 2 and return - 1 ; Check if N is odd ; Check if column required to be corrected is odd and then assign N - colSwap to colSwap ; Check if rows required to be corrected is odd and then assign N - rowSwap to rowSwap ; Take min of colSwap and N - colSwap ; Take min of rowSwap and N - rowSwap ; Finally return answer ; Driver Code ; Given matrix ; Function Call ; Print answer | #include <bits/stdc++.h> NEW_LINE using namespace std ; int minSwaps ( vector < vector < int > > & b ) { int n = b . size ( ) ; for ( int i = 0 ; i < n ; i ++ ) { for ( int j = 0 ; j < n ; j ++ ) { if ( b [ 0 ] [ 0 ] ^ b [ 0 ] [ j ] ^ b [ i ] [ 0 ] ^ b [ i ] [ j ] ) return -1 ; } } int rowSum = 0 ; int colSum = 0 ; int rowSwap = 0 ; int colSwap = 0 ; for ( int i = 0 ; i < n ; i ++ ) { rowSum += b [ i ] [ 0 ] ; colSum += b [ 0 ] [ i ] ; rowSwap += b [ i ] [ 0 ] == i % 2 ; colSwap += b [ 0 ] [ i ] == i % 2 ; } if ( rowSum != n / 2 && rowSum != ( n + 1 ) / 2 ) return -1 ; if ( colSum != n / 2 && colSum != ( n + 1 ) / 2 ) return -1 ; if ( n % 2 == 1 ) { if ( colSwap % 2 ) colSwap = n - colSwap ; if ( rowSwap % 2 ) rowSwap = n - rowSwap ; } else { colSwap = min ( colSwap , n - colSwap ) ; rowSwap = min ( rowSwap , n - rowSwap ) ; } return ( rowSwap + colSwap ) / 2 ; } int main ( ) { vector < vector < int > > M = { { 0 , 1 , 1 , 0 } , { 0 , 1 , 1 , 0 } , { 1 , 0 , 0 , 1 } , { 1 , 0 , 0 , 1 } } ; int ans = minSwaps ( M ) ; cout << ans ; } |
Minimum number of coins having value equal to powers of 2 required to obtain N | C ++ program for above approach ; Function to count of set bit in N ; Stores count of set bit in N ; Iterate over the range [ 0 , 31 ] ; If current bit is set ; Update result ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; void count_setbit ( int N ) { int result = 0 ; for ( int i = 0 ; i < 32 ; i ++ ) { if ( ( 1 << i ) & N ) { result ++ ; } } cout << result << endl ; } int main ( ) { int N = 43 ; count_setbit ( N ) ; return 0 ; } |
Evaluate the expression ( N1 * ( N | C ++ program to implement the above approach ; Function to find the value of the expression ( N ^ 1 * ( N 1 ) ^ 2 * ... * 1 ^ N ) % ( 109 + 7 ) . ; factorial [ i ] : Stores factorial of i ; Base Case for factorial ; Precompute the factorial ; dp [ N ] : Stores the value of the expression ( N ^ 1 * ( N 1 ) ^ 2 * ... * 1 ^ N ) % ( 109 + 7 ) . ; Update dp [ i ] ; Return the answer . ; Driver Code ; Function call | #include <bits/stdc++.h> NEW_LINE using namespace std ; #define mod 1000000007 NEW_LINE int ValOfTheExpression ( int n ) { int factorial [ n ] = { 0 } ; factorial [ 0 ] = factorial [ 1 ] = 1 ; for ( int i = 2 ; i <= n ; i ++ ) { factorial [ i ] = ( ( factorial [ i - 1 ] % mod ) * ( i % mod ) ) % mod ; } int dp [ n ] = { 0 } ; dp [ 1 ] = 1 ; for ( int i = 2 ; i <= n ; i ++ ) { dp [ i ] = ( ( dp [ i - 1 ] % mod ) * ( factorial [ i ] % mod ) ) % mod ; } return dp [ n ] ; } int main ( ) { int n = 4 ; cout << ValOfTheExpression ( n ) << " STRNEWLINE " ; } |
Chocolate Distribution Problem | Set 2 | C ++ program for the above approach ; FUnction to print minimum number of candies required ; Distribute 1 chocolate to each ; Traverse from left to right ; Traverse from right to left ; Initialize sum ; Find total sum ; Return sum ; Driver Code ; Given array ; Size of the given array | #include <iostream> NEW_LINE using namespace std ; void minChocolates ( int A [ ] , int N ) { int B [ N ] ; for ( int i = 0 ; i < N ; i ++ ) { B [ i ] = 1 ; } for ( int i = 1 ; i < N ; i ++ ) { if ( A [ i ] > A [ i - 1 ] ) B [ i ] = B [ i - 1 ] + 1 ; else B [ i ] = 1 ; } for ( int i = N - 2 ; i >= 0 ; i -- ) { if ( A [ i ] > A [ i + 1 ] ) B [ i ] = max ( B [ i + 1 ] + 1 , B [ i ] ) ; else B [ i ] = max ( B [ i ] , 1 ) ; } int sum = 0 ; for ( int i = 0 ; i < N ; i ++ ) { sum += B [ i ] ; } cout << sum << " STRNEWLINE " ; } int main ( ) { int A [ ] = { 23 , 14 , 15 , 14 , 56 , 29 , 14 } ; int N = sizeof ( A ) / sizeof ( A [ 0 ] ) ; minChocolates ( A , N ) ; } |
Construct longest possible sequence of unique elements with given LCM | C ++ program to implement the above approach ; Function to construct an array of unique elements whose LCM is N ; Stores array elements whose LCM is N ; Iterate over the range [ 1 , sqrt ( N ) ] ; If N is divisible by i ; Insert i into newArr [ ] ; If N is not perfect square ; Sort the array newArr [ ] ; Print array elements ; Driver Code ; Given N ; Function Call | #include <bits/stdc++.h> NEW_LINE using namespace std ; void constructArrayWithGivenLCM ( int N ) { vector < int > newArr ; for ( int i = 1 ; i * i <= N ; i ++ ) { if ( N % i == 0 ) { newArr . push_back ( i ) ; if ( N / i != i ) { newArr . push_back ( N / i ) ; } } } sort ( newArr . begin ( ) , newArr . end ( ) ) ; for ( auto i : newArr ) { cout << i << " β " ; } } int main ( ) { int N = 12 ; constructArrayWithGivenLCM ( N ) ; return 0 ; } |
Count numbers from given range having odd digits at odd places and even digits at even places | C ++ program to implement the above approach ; Function to calculate 5 ^ p ; Stores the result ; Multiply 5 p times ; Return the result ; Function to count all numbers upto N having odd digits at odd places and even digits at even places ; Stores the count ; Stores the digits of N ; Insert the digits of N ; Reverse the vector to arrange the digits from first to last ; Stores count of digits of n ; Stores the count of numbers with i digits ; If the last digit is reached , subtract numbers eceeding range ; Iterate over all the places ; Stores the digit in the pth place ; Stores the count of numbers having a digit greater than x in the p - th position ; Calculate the count of numbers exceeding the range if p is even ; Calculate the count of numbers exceeding the range if p is odd ; Subtract the count of numbers exceeding the range from total count ; If the parity of p and the parity of x are not same ; Add count of numbers having i digits and satisfies the given conditions ; Return the total count of numbers till n ; Function to calculate the count of numbers from given range having odd digits places and even digits at even places ; Count of numbers in range [ L , R ] = Count of numbers till R - ; Count of numbers till ( L - 1 ) ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; #define ll long long NEW_LINE ll getPower ( int p ) { ll res = 1 ; while ( p -- ) { res *= 5 ; } return res ; } ll countNumbersUtil ( ll N ) { ll count = 0 ; vector < int > digits ; while ( N ) { digits . push_back ( N % 10 ) ; N /= 10 ; } reverse ( digits . begin ( ) , digits . end ( ) ) ; int D = digits . size ( ) ; for ( int i = 1 ; i <= D ; i ++ ) { ll res = getPower ( i ) ; if ( i == D ) { for ( int p = 1 ; p <= D ; p ++ ) { int x = digits [ p - 1 ] ; ll tmp = 0 ; if ( p % 2 == 0 ) { tmp = ( 5 - ( x / 2 + 1 ) ) * getPower ( D - p ) ; } else { tmp = ( 5 - ( x + 1 ) / 2 ) * getPower ( D - p ) ; } res -= tmp ; if ( p % 2 != x % 2 ) { break ; } } } count += res ; } return count ; } void countNumbers ( ll L , ll R ) { cout << ( countNumbersUtil ( R ) - countNumbersUtil ( L - 1 ) ) << endl ; } int main ( ) { ll L = 128 , R = 162 ; countNumbers ( L , R ) ; return 0 ; } |
Sum of first N natural numbers with alternate signs | C ++ program to implement the above approach ; Function to find the sum of first N natural numbers with alternate signs ; Stores sum of alternate sign of first N natural numbers ; If is an even number ; Update alternateSum ; If i is an odd number ; Update alternateSum ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int alternatingSumOfFirst_N ( int N ) { int alternateSum = 0 ; for ( int i = 1 ; i <= N ; i ++ ) { if ( i % 2 == 0 ) { alternateSum += - i ; } else { alternateSum += i ; } } return alternateSum ; } int main ( ) { int N = 6 ; cout << alternatingSumOfFirst_N ( N ) ; return 0 ; } |
Sum of all numbers up to N that are co | C ++ program for the above approach ; Function to return gcd of a and b ; Base Case ; Recursive GCD ; Function to calculate the sum of all numbers till N that are coprime with N ; Stores the resultant sum ; Iterate over [ 1 , N ] ; If gcd is 1 ; Update sum ; Return the final sum ; Driver Code ; Given N ; Function Call | #include <iostream> NEW_LINE using namespace std ; int gcd ( int a , int b ) { if ( a == 0 ) return b ; return gcd ( b % a , a ) ; } int findSum ( unsigned int N ) { unsigned int sum = 0 ; for ( int i = 1 ; i < N ; i ++ ) { if ( gcd ( i , N ) == 1 ) { sum += i ; } } return sum ; } int main ( ) { int N = 5 ; cout << findSum ( N ) ; return 0 ; } |
Count all distinct pairs of repeating elements from the array for every array element | C ++ program for the above approach ; Function to print the required count of pairs excluding the current element ; Store the frequency ; Find all the count ; Delete the contribution of each element for equal pairs ; Print the answer ; Driver Code ; Given array arr [ ] ; Function Call | #include <bits/stdc++.h> NEW_LINE #define int long long int NEW_LINE using namespace std ; void solve ( int arr [ ] , int n ) { unordered_map < int , int > mp ; for ( int i = 0 ; i < n ; i ++ ) { mp [ arr [ i ] ] ++ ; } int cnt = 0 ; for ( auto x : mp ) { cnt += ( ( x . second ) * ( x . second - 1 ) / 2 ) ; } int ans [ n ] ; for ( int i = 0 ; i < n ; i ++ ) { ans [ i ] = cnt - ( mp [ arr [ i ] ] - 1 ) ; } for ( int i = 0 ; i < n ; i ++ ) { cout << ans [ i ] << " β " ; } } int32_t main ( ) { int arr [ ] = { 1 , 1 , 2 , 1 , 2 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; solve ( arr , N ) ; return 0 ; } |
Mode in a stream of integers ( running integers ) | C ++ program to implement the above approach ; Function that prints the Mode values ; Map used to mp integers to its frequency ; To store the maximum frequency ; To store the element with the maximum frequency ; Loop used to read the elements one by one ; Updates the frequency of that element ; Checks for maximum Number of occurrence ; Updates the maximum frequency ; Updates the Mode ; Driver Code ; Function call | #include <bits/stdc++.h> NEW_LINE using namespace std ; void findMode ( int a [ ] , int n ) { map < int , int > mp ; int max = 0 ; int mode = 0 ; for ( int i = 0 ; i < n ; i ++ ) { mp [ a [ i ] ] ++ ; if ( mp [ a [ i ] ] >= max ) { max = mp [ a [ i ] ] ; mode = a [ i ] ; } cout << mode << " β " ; } } int main ( ) { int arr [ ] = { 2 , 7 , 3 , 2 , 5 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; findMode ( arr , n ) ; return 0 ; } |
Count of distinct numbers formed by shuffling the digits of a large number N | C ++ program for the above approach ; Recursive function to return the value of ( x ^ n ) % m ; Base Case ; If N is even ; Else N is odd ; Function to find modular inverse of a number x under modulo m ; Using Fermat 's little theorem ; Function to count of numbers formed by shuffling the digits of a large number N ; Modulo value ; Array to store the factorials upto the maximum value of N ; Store factorial of i at index i ; To store count of occurrence of a digit ; Increment the count of digit occured ; Assign the factorial of length of input ; Multiplying result with the modulo multiplicative inverse of factorial of count of i ; Print the result ; Driver Code ; Given Number as string ; Function call | #include <bits/stdc++.h> NEW_LINE using namespace std ; #define ll long long int NEW_LINE ll modexp ( ll x , ll n , ll m ) { if ( n == 0 ) { return 1 ; } else if ( n % 2 == 0 ) { return modexp ( ( x * x ) % m , n / 2 , m ) ; } else { return ( x * modexp ( ( x * x ) % m , ( n - 1 ) / 2 , m ) % m ) ; } } ll modInverse ( ll x , ll m ) { return modexp ( x , m - 2 , m ) ; } void countNumbers ( string N ) { ll m = 1000000007 ; ll factorial [ 100001 ] ; factorial [ 0 ] = 1 ; for ( ll i = 1 ; i < 100001 ; i ++ ) { factorial [ i ] = ( factorial [ i - 1 ] * i ) % m ; } ll count [ 10 ] ; for ( ll i = 0 ; i < 10 ; i ++ ) { count [ i ] = 0 ; } ll length = N . length ( ) ; for ( ll i = 0 ; i < length ; i ++ ) count [ N [ i ] - '0' ] ++ ; ll result = factorial [ length ] ; for ( ll i = 0 ; i < 10 ; i ++ ) { result = ( result * modInverse ( factorial [ count [ i ] ] , m ) ) % m ; } cout << result ; } int main ( ) { string N = "0223" ; countNumbers ( N ) ; return 0 ; } |
Find prime factors of Array elements whose sum of exponents is divisible by K | C ++ program for the above approach ; To store the smallest prime factor till 10 ^ 5 ; Function to compute smallest prime factor array ; Initialize the spf array first element ; Marking smallest prime factor for every number to be itself ; Separately marking smallest prime factor for every even number as 2 ; Checking if i is prime ; Marking SPF for all numbers divisible by i ; Marking spf [ j ] if it is not previously marked ; Function that finds minimum operation ; Create a spf [ ] array ; Map created to store the unique prime numbers ; To store the result ; To store minimum operations ; To store every unique prime number ; Erase 1 as a key because it is not a prime number ; First Prime Number ; Frequency is divisible by K then insert primeNum in the result [ ] ; Print the elements if it exists ; Driver Code ; Given array arr [ ] ; Given K ; Function Call | #include <iostream> NEW_LINE #include <unordered_map> NEW_LINE #include <vector> NEW_LINE using namespace std ; int spf [ 10001 ] ; void spf_array ( int spf [ ] ) { spf [ 1 ] = 1 ; for ( int i = 2 ; i < 1000 ; i ++ ) spf [ i ] = i ; for ( int i = 4 ; i < 1000 ; i += 2 ) spf [ i ] = 2 ; for ( int i = 3 ; i * i < 1000 ; i ++ ) { if ( spf [ i ] == i ) { for ( int j = i * i ; j < 1000 ; j += i ) if ( spf [ j ] == j ) spf [ j ] = i ; } } } void frequent_prime ( int arr [ ] , int N , int K ) { spf_array ( spf ) ; unordered_map < int , int > Hmap ; vector < int > result ; int i = 0 ; int c = 0 ; for ( i = 0 ; i < N ; i ++ ) { int x = arr [ i ] ; while ( x != 1 ) { Hmap [ spf [ x ] ] = Hmap [ spf [ x ] ] + 1 ; x = x / spf [ x ] ; } } Hmap . erase ( 1 ) ; for ( auto x : Hmap ) { int primeNum = x . first ; int frequency = x . second ; if ( frequency % K == 0 ) { result . push_back ( primeNum ) ; } } if ( result . size ( ) > 0 ) { for ( auto & it : result ) { cout << it << ' β ' ; } } else { cout << " { } " ; } } int main ( ) { int arr [ ] = { 1 , 4 , 6 } ; int K = 1 ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; frequent_prime ( arr , N , K ) ; } |
Generate first K multiples of N using Bitwise operators | C ++ program to implement the above approach ; Function to print the first K multiples of N ; Print the value of N * i ; Iterate each bit of N and add pow ( 2 , pos ) , where pos is the index of each set bit ; Check if current bit at pos j is fixed or not ; For next set bit ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; void Kmultiples ( int n , int k ) { int a = n ; for ( int i = 1 ; i <= k ; i ++ ) { cout << n << " β * β " << i << " β = β " << a << endl ; int j = 0 ; while ( n >= ( 1 << j ) ) { a += n & ( 1 << j ) ; j ++ ; } } } int main ( ) { int N = 16 , K = 7 ; Kmultiples ( N , K ) ; return 0 ; } |
Least Square Regression Line | C ++ program to find the regression line ; Function to calculate b ; sum of array x ; sum of array y ; for sum of product of x and y ; sum of square of x ; Function to find the least regression line ; Finding b ; Calculating a ; Printing regression line ; Driver code ; Statistical data | #include <bits/stdc++.h> NEW_LINE using namespace std ; double calculateB ( int x [ ] , int y [ ] , int n ) { int sx = accumulate ( x , x + n , 0 ) ; int sy = accumulate ( y , y + n , 0 ) ; int sxsy = 0 ; int sx2 = 0 ; for ( int i = 0 ; i < n ; i ++ ) { sxsy += x [ i ] * y [ i ] ; sx2 += x [ i ] * x [ i ] ; } double b = ( double ) ( n * sxsy - sx * sy ) / ( n * sx2 - sx * sx ) ; return b ; } void leastRegLine ( int X [ ] , int Y [ ] , int n ) { double b = calculateB ( X , Y , n ) ; int meanX = accumulate ( X , X + n , 0 ) / n ; int meanY = accumulate ( Y , Y + n , 0 ) / n ; double a = meanY - b * meanX ; cout << ( " Regression β line : " ) << endl ; cout << ( " Y β = β " ) ; printf ( " % .3f β + β " , a ) ; printf ( " % .3f β * X " , b ) ; } int main ( ) { int X [ ] = { 95 , 85 , 80 , 70 , 60 } ; int Y [ ] = { 90 , 80 , 70 , 65 , 60 } ; int n = sizeof ( X ) / sizeof ( X [ 0 ] ) ; leastRegLine ( X , Y , n ) ; } |
Count of repeating digits in a given Number | C ++ program for the above approach ; Function that returns the count of repeating digits of the given number ; Initialize a variable to store count of Repeating digits ; Initialize cnt array to store digit count ; Iterate through the digits of N ; Retrieve the last digit of N ; Increase the count of digit ; Remove the last digit of N ; Iterate through the cnt array ; If frequency of digit is greater than 1 ; Increment the count of Repeating digits ; Return count of repeating digit ; Driver Code ; Given array arr [ ] ; Function Call | #include <bits/stdc++.h> NEW_LINE using namespace std ; int countRepeatingDigits ( int N ) { int res = 0 ; int cnt [ 10 ] = { 0 } ; while ( N > 0 ) { int rem = N % 10 ; cnt [ rem ] ++ ; N = N / 10 ; } for ( int i = 0 ; i < 10 ; i ++ ) { if ( cnt [ i ] > 1 ) { res ++ ; } } return res ; } int main ( ) { int N = 12 ; cout << countRepeatingDigits ( N ) ; return 0 ; } |
Find temperature of missing days using given sum and average | C ++ program for the above approach ; Function for finding the temperature ; Store Day1 - Day2 in diff ; Remaining from s will be Day1 ; Print Day1 and Day2 ; Driver Code ; Functions | #include <bits/stdc++.h> NEW_LINE using namespace std ; void findTemperature ( int x , int y , int s ) { double Day1 , Day2 ; double diff = ( x - y ) * 6 ; Day2 = ( diff + s ) / 2 ; Day1 = s - Day2 ; cout << " Day1 β : β " << Day1 << endl ; cout << " Day2 β : β " << Day2 << endl ; } int main ( ) { int x = 5 , y = 10 , s = 40 ; findTemperature ( x , y , s ) ; return 0 ; } |
Find two numbers whose sum is N and does not contain any digit as K | C ++ program for the above approach ; Function to find two numbers whose sum is N and do not contain any digit as k ; Check every number i and ( n - i ) ; Check if i and n - i doesn 't contain k in them print i and n-i ; Check if flag is 0 then print - 1 ; Driver Code ; Given N and K ; Function call | #include <bits/stdc++.h> NEW_LINE using namespace std ; int freqCount ( string str , char k ) { int count = 0 ; for ( int i = 0 ; i < str . size ( ) ; i ++ ) { if ( str [ i ] == k ) count ++ ; } return count ; } void findAandB ( int n , int k ) { int flag = 0 ; for ( int i = 1 ; i < n ; i ++ ) { if ( freqCount ( to_string ( i ) , ( char ) ( k + 48 ) ) == 0 and freqCount ( to_string ( n - i ) , ( char ) ( k + 48 ) ) == 0 ) { cout << " ( " << i << " , β " << n - i << " ) " ; flag = 1 ; break ; } } if ( flag == 0 ) cout << -1 ; } int main ( ) { int N = 100 ; int K = 0 ; findAandB ( N , K ) ; return 0 ; } |
Find the value of P and modular inverse of Q modulo 998244353 | C ++ implementation to find the value of P . Q - 1 mod 998244353 ; Function to find the value of P * Q ^ - 1 mod 998244353 ; Loop to find the value until the expo is not zero ; Multiply p with q if expo is odd ; Reduce the value of expo by 2 ; Driver code ; Function Call | #include <bits/stdc++.h> NEW_LINE using namespace std ; long long calculate ( long long p , long long q ) { long long mod = 998244353 , expo ; expo = mod - 2 ; while ( expo ) { if ( expo & 1 ) { p = ( p * q ) % mod ; } q = ( q * q ) % mod ; expo >>= 1 ; } return p ; } int main ( ) { int p = 1 , q = 4 ; cout << calculate ( p , q ) << ' ' ; return 0 ; } |
Find two numbers with given sum and maximum possible LCM | C ++ program of the above approach ; Function that print two numbers with the sum X and maximum possible LCM ; variables to store the result ; If X is odd ; If X is even ; If floor ( X / 2 ) is even ; If floor ( X / 2 ) is odd ; Print the result ; Driver Code ; Given Number ; Function call | #include <bits/stdc++.h> NEW_LINE using namespace std ; void maxLCMWithGivenSum ( int X ) { int A , B ; if ( X & 1 ) { A = X / 2 ; B = X / 2 + 1 ; } else { if ( ( X / 2 ) % 2 == 0 ) { A = X / 2 - 1 ; B = X / 2 + 1 ; } else { A = X / 2 - 2 ; B = X / 2 + 2 ; } } cout << A << " β " << B << endl ; } int main ( ) { int X = 30 ; maxLCMWithGivenSum ( X ) ; return 0 ; } |
Length of longest subarray whose sum is not divisible by integer K | C ++ Program to find the length of the longest subarray whose sum is not divisible by integer K ; Function to find the longest subarray with sum is not divisible by k ; left is the index of the leftmost element that is not divisible by k ; right is the index of the rightmost element that is not divisible by k ; sum of the array ; Find the element that is not multiple of k ; left = - 1 means we are finding the leftmost element that is not divisible by k ; Updating the rightmost element ; update the sum of the array up to the index i ; Check if the sum of the array is not divisible by k , then return the size of array ; All elements of array are divisible by k , then no such subarray possible so return - 1 ; length of prefix elements that can be removed ; length of suffix elements that can be removed ; Return the length of subarray after removing the elements which have lesser number of elements ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int MaxSubarrayLength ( int arr [ ] , int n , int k ) { int left = -1 ; int right ; int sum = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( ( arr [ i ] % k ) != 0 ) { if ( left == -1 ) { left = i ; } right = i ; } sum += arr [ i ] ; } if ( ( sum % k ) != 0 ) { return n ; } else if ( left == -1 ) { return -1 ; } else { int prefix_length = left + 1 ; int suffix_length = n - right ; return n - min ( prefix_length , suffix_length ) ; } } int main ( ) { int arr [ ] = { 6 , 3 , 12 , 15 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; int K = 3 ; cout << MaxSubarrayLength ( arr , n , K ) ; return 0 ; } |
Minimum steps to convert X to Y by repeated division and multiplication | C ++ implementation to find minimum steps to convert X to Y by repeated division and multiplication ; Check if X is greater than Y then swap the elements ; Check if X equals Y ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int solve ( int X , int Y ) { if ( X > Y ) { int temp = X ; X = Y ; Y = temp ; } if ( X == Y ) cout << 0 << endl ; else if ( Y % X == 0 ) cout << 1 << endl ; else cout << 2 << endl ; } int main ( ) { int X = 8 , Y = 13 ; solve ( X , Y ) ; return 0 ; } |
Count quadruplets ( A , B , C , D ) till N such that sum of square of A and B is equal to that of C and D | C ++ program for the above approach ; Function to count the quadruples ; Counter variable ; Map to store the sum of pair ( a ^ 2 + b ^ 2 ) ; Iterate till N ; Calculate a ^ 2 + b ^ 2 ; Increment the value in map ; Check if this sum was also in a ^ 2 + b ^ 2 ; Return the count ; Driver Code ; Given N ; Function Call | #include <bits/stdc++.h> NEW_LINE using namespace std ; typedef long long int ll ; ll countQuadraples ( ll N ) { ll cnt = 0 ; map < ll , ll > m ; for ( ll a = 1 ; a <= N ; a ++ ) { for ( ll b = 1 ; b <= N ; b ++ ) { ll x = a * a + b * b ; m [ x ] += 1 ; } } for ( ll c = 1 ; c <= N ; c ++ ) { for ( ll d = 1 ; d <= N ; d ++ ) { ll x = c * c + d * d ; if ( m . find ( x ) != m . end ( ) ) cnt += m [ x ] ; } } return cnt ; } int main ( ) { ll N = 2 ; cout << countQuadraples ( N ) << endl ; return 0 ; } |
Count of distinct index pair ( i , j ) such that element sum of First Array is greater | C ++ program for the above problem ; function to find the number of pairs satisfying the given cond . ; variables used for traversal ; count variable to store the count of possible pairs ; Nested loop to find out the possible pairs ; Check if the given condition is satisfied or not . If yes then increment the count . ; Return the count value ; Driver Code ; Size of the arrays ; Initialise the arrays ; function call that returns the count of possible pairs | #include <bits/stdc++.h> NEW_LINE using namespace std ; int count_pairs ( int a [ ] , int b [ ] , int N ) { int i , j ; int count = 0 ; for ( i = 0 ; i < ( N - 1 ) ; i ++ ) { for ( j = ( i + 1 ) ; j < N ; j ++ ) { if ( ( a [ i ] + a [ j ] ) > ( b [ i ] + b [ j ] ) ) { count ++ ; } } } return count ; } int main ( ) { int N = 5 ; int a [ N ] = { 1 , 2 , 3 , 4 , 5 } ; int b [ N ] = { 2 , 5 , 6 , 1 , 9 } ; cout << count_pairs ( a , b , N ) << endl ; return 0 ; } |
Count of distinct index pair ( i , j ) such that element sum of First Array is greater | C ++ program of the above approach ; Function to find the number of pairs . ; Array c [ ] where c [ i ] = a [ i ] - b [ i ] ; Sort the array c ; Initialise answer as 0 ; Iterate from index 0 to n - 1 ; If c [ i ] <= 0 then in the sorted array c [ i ] + c [ pos ] can never greater than 0 where pos < i ; Find the minimum index such that c [ i ] + c [ j ] > 0 which is equivalent to c [ j ] >= - c [ i ] + 1 ; Add ( i - pos ) to answer ; return the answer ; Driver code ; Number of elements in a and b ; array a ; array b | #include <bits/stdc++.h> NEW_LINE using namespace std ; int numberOfPairs ( int * a , int * b , int n ) { int c [ n ] ; for ( int i = 0 ; i < n ; i ++ ) { c [ i ] = a [ i ] - b [ i ] ; } sort ( c , c + n ) ; int answer = 0 ; for ( int i = 1 ; i < n ; i ++ ) { if ( c [ i ] <= 0 ) continue ; int pos = lower_bound ( c , c + n , - c [ i ] + 1 ) - c ; answer += ( i - pos ) ; } return answer ; } int32_t main ( ) { int n = 5 ; int a [ ] = { 1 , 2 , 3 , 4 , 5 } ; int b [ ] = { 2 , 5 , 6 , 1 , 9 } ; cout << numberOfPairs ( a , b , n ) << endl ; return 0 ; } |
Find K for every Array element such that at least K prefixes are Γ’ β°Β₯ K | C ++ program for the above approach ; Function to find the K - value for every index in the array ; Multiset to store the array in the form of red - black tree ; Iterating over the array ; Inserting the current value in the multiset ; Condition to check if the smallest value in the set is less than it 's size ; Erase the smallest value ; h - index value will be the size of the multiset ; Driver Code ; array ; Size of the array ; function call | #include <bits/stdc++.h> NEW_LINE using namespace std ; int print_h_index ( int arr [ ] , int N ) { multiset < int > ms ; for ( int i = 0 ; i < N ; i ++ ) { ms . insert ( arr [ i ] ) ; if ( * ms . begin ( ) < ms . size ( ) ) { ms . erase ( ms . begin ( ) ) ; } cout << ms . size ( ) << " β " ; } } int main ( ) { int arr [ ] = { 9 , 10 , 7 , 5 , 0 , 10 , 2 , 0 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; print_h_index ( arr , N ) ; return 0 ; } |
Prefix Product Array | C ++ Program to generate Prefix Product Array ; Function to generate prefix product array ; Update the array with the product of prefixes ; Print the array ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int prefixProduct ( int a [ ] , int n ) { for ( int i = 1 ; i < n ; i ++ ) { a [ i ] = a [ i ] * a [ i - 1 ] ; } for ( int j = 0 ; j < n ; j ++ ) { cout << a [ j ] << " , β " ; } return 0 ; } int main ( ) { int arr [ ] = { 2 , 4 , 6 , 5 , 10 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; prefixProduct ( arr , N ) ; return 0 ; } |
Count of ways to distribute N items among 3 people with one person receiving maximum | C ++ program to find the number of ways to distribute N item among three people such that one person always gets the maximum value ; Function to find the number of ways to distribute N items among 3 people ; No distribution possible ; Total number of ways to distribute N items among 3 people ; Store the number of distributions which are not possible ; Count possibilities of two persons receiving the maximum ; If N is divisible by 3 ; Return the final count of ways to distribute ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int countWays ( int N ) { if ( N < 4 ) return 0 ; int ans = ( ( N - 1 ) * ( N - 2 ) ) / 2 ; int s = 0 ; for ( int i = 2 ; i <= N - 3 ; i ++ ) { for ( int j = 1 ; j < i ; j ++ ) { if ( N == 2 * i + j ) s ++ ; } } if ( N % 3 == 0 ) s = 3 * s + 1 ; else s = 3 * s ; return ans - s ; } int main ( ) { int N = 10 ; cout << countWays ( N ) ; return 0 ; } |
Magnanimous Numbers | C ++ implementation to check if a number is Magnanimous ; Function to check if n is prime ; Corner cases ; This is checked so that we can skip middle five numbers in below loop ; Function to check if the number is Magnanimous or not ; converting the number to string ; finding length of string ; number should not be of single digit ; loop to find all left and right part of the string ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; bool isPrime ( int n ) { if ( n <= 1 ) return false ; if ( n <= 3 ) return true ; if ( n % 2 == 0 n % 3 == 0 ) return false ; for ( int i = 5 ; i * i <= n ; i = i + 6 ) if ( n % i == 0 || n % ( i + 2 ) == 0 ) return false ; return true ; } bool isMagnanimous ( int N ) { string s = to_string ( N ) ; int l = s . length ( ) ; if ( l < 2 ) return false ; for ( int i = 0 ; i < l - 1 ; i ++ ) { string left = s . substr ( 0 , i + 1 ) ; string right = s . substr ( i + 1 ) ; int x = stoi ( left ) ; int y = stoi ( right ) ; if ( ! isPrime ( x + y ) ) return false ; } return true ; } int main ( ) { int N = 12 ; isMagnanimous ( N ) ? cout << " Yes " : cout << " No " ; return 0 ; } |
Honaker Prime Number | C ++ program for the above approach ; Function to precompute the position of every prime number using Sieve ; 0 and 1 are not prime numbers ; Variable to store the position ; Incrementing the position for every prime number ; Function to get sum of digits ; Function to check whether the given number is Honaker Prime number or not ; Driver Code ; Precompute the prime numbers till 10 ^ 6 ; Given Number ; Function Call | #include <bits/stdc++.h> NEW_LINE #define limit 10000000 NEW_LINE using namespace std ; int position [ limit + 1 ] ; void sieve ( ) { position [ 0 ] = -1 , position [ 1 ] = -1 ; int pos = 0 ; for ( int i = 2 ; i <= limit ; i ++ ) { if ( position [ i ] == 0 ) { position [ i ] = ++ pos ; for ( int j = i * 2 ; j <= limit ; j += i ) position [ j ] = -1 ; } } } int getSum ( int n ) { int sum = 0 ; while ( n != 0 ) { sum = sum + n % 10 ; n = n / 10 ; } return sum ; } bool isHonakerPrime ( int n ) { int pos = position [ n ] ; if ( pos == -1 ) return false ; return getSum ( n ) == getSum ( pos ) ; } int main ( ) { sieve ( ) ; int N = 121 ; if ( isHonakerPrime ( N ) ) cout << " Yes " ; else cout << " No " ; } |
Check if Matrix sum is prime or not | C ++ implementation to check if the sum of matrix is prime or not ; Function to check whether a number is prime or not ; Corner case ; Check from 2 to n - 1 ; Function for to find the sum of the given matrix ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; const int N = 4 , M = 5 ; bool isPrime ( int n ) { if ( n <= 1 ) return false ; for ( int i = 2 ; i <= sqrt ( n ) ; i ++ ) if ( n % i == 0 ) return false ; return true ; } int takeSum ( int a [ N ] [ M ] ) { int s = 0 ; for ( int i = 0 ; i < N ; i ++ ) for ( int j = 0 ; j < M ; j ++ ) s += a [ i ] [ j ] ; return s ; } int main ( ) { int a [ N ] [ M ] = { { 1 , 2 , 3 , 4 , 2 } , { 0 , 1 , 2 , 3 , 34 } , { 0 , 34 , 21 , 12 , 12 } , { 1 , 2 , 3 , 6 , 6 } } ; int sum = takeSum ( a ) ; if ( isPrime ( sum ) ) cout << " YES " << endl ; else cout << " NO " << endl ; return 0 ; } |
Sum of sum | C ++ program to implement the above approach ; Function to find the sum ; Calculate sum - series for every natural number and add them ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; static long sumOfSumSeries ( int N ) { long sum = 0L ; for ( int i = 1 ; i <= N ; i ++ ) { sum = sum + ( i * ( i + 1 ) ) / 2 ; } return sum ; } int main ( ) { int N = 5 ; cout << sumOfSumSeries ( N ) ; } |
Sum of sum | C ++ program to implement the above approach ; Function to find the sum ; Driver code | #include <iostream> NEW_LINE #include <math.h> NEW_LINE using namespace std ; long sumOfSumSeries ( int n ) { return ( n * ( n + 1 ) * ( n + 2 ) ) / 6 ; } int main ( ) { int N = 5 ; cout << sumOfSumSeries ( N ) ; return 0 ; } |
Tetradic Primes | C ++ implementation to print all Tetradic primes smaller than or equal to N . ; Function to check if the number N having all digits lies in the set ( 0 , 1 , 8 ) ; Function to check if the number N is palindrome ; Function to check if a number N is Tetradic ; Function to generate all primes and checking whether number is Tetradic or not ; 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 ; Update all multiples of p ; Print all Tetradic prime numbers ; Checking whether the given number is prime Tetradic or not ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; bool isContaindigit ( int n ) { while ( n > 0 ) { if ( ! ( n % 10 == 0 n % 10 == 1 n % 10 == 8 ) ) return false ; n = n / 10 ; } return true ; } bool ispalindrome ( int n ) { string temp = to_string ( n ) ; int l = temp . length ( ) ; for ( int i = 0 ; i < l / 2 ; i ++ ) { if ( temp [ i ] != temp [ l - i - 1 ] ) return false ; } return true ; } bool isTetradic ( int n ) { if ( ispalindrome ( n ) && isContaindigit ( n ) ) return true ; return false ; } void printTetradicPrimesLessThanN ( int n ) { bool prime [ n + 1 ] ; memset ( prime , true , sizeof ( prime ) ) ; int p = 2 ; while ( p * p <= n ) { if ( prime [ p ] ) { for ( int i = p * 2 ; i < n + 1 ; i += p ) prime [ i ] = false ; } p += 1 ; } for ( p = 2 ; p < n + 1 ; p ++ ) { if ( prime [ p ] && isTetradic ( p ) ) cout << p << " β " ; } } int main ( ) { int n = 1000 ; printTetradicPrimesLessThanN ( n ) ; return 0 ; } |
Astonishing Numbers | C ++ implementation for the above approach ; Function to concatenate two integers into one ; Convert both the integers to string ; Concatenate both strings ; Convert the concatenated string to integer ; return the formed integer ; Function to check if N is a Astonishing number ; Loop to find sum of all integers from i till the sum becomes >= n ; variable to store sum of all integers from i to j and check if sum and concatenation equals n or not ; finding concatenation of i and j ; condition for Astonishing number ; Driver Code ; Given Number ; Function Call | #include <bits/stdc++.h> NEW_LINE using namespace std ; int concat ( int a , int b ) { string s1 = to_string ( a ) ; string s2 = to_string ( b ) ; string s = s1 + s2 ; int c = stoi ( s ) ; return c ; } bool isAstonishing ( int n ) { for ( int i = 1 ; i < n ; i ++ ) { int sum = 0 ; for ( int j = i ; j < n ; j ++ ) { sum += j ; if ( sum == n ) { int concatenation = concat ( i , j ) ; if ( concatenation == n ) { return true ; } } } } return false ; } int main ( ) { int n = 429 ; if ( isAstonishing ( n ) ) cout << " Yes " ; else cout << " No " ; return 0 ; } |
Digitally balanced numbers | C ++ implementation to check if a number is a digitally balanced number ; Function to check if the digits in the number is the same number of digits ; Loop to iterate over the digits of the number N ; Loop to iterate over the map ; Driver Code ; function to check | #include <bits/stdc++.h> NEW_LINE using namespace std ; int checkSame ( int n , int b ) { map < int , int > m ; while ( n != 0 ) { int r = n % b ; n = n / b ; m [ r ] ++ ; } int last = -1 ; for ( auto i = m . begin ( ) ; i != m . end ( ) ; i ++ ) { if ( last != -1 && i -> second != last ) { return false ; } else { last = i -> second ; } } } int main ( ) { int n = 9 ; int base = 2 ; if ( checkSame ( n , base ) ) cout << " Yes " ; else cout << " NO " ; return 0 ; } |
Sum of series formed by difference between product and sum of N natural numbers | C ++ program to implement the above approach ; Function to calculate the sum upto Nth term ; Stores the sum of the series ; Stores the product of natural numbers upto the current term ; Stores the sum of natural numbers upto the upto current term ; Generate the remaining terms and calculate sum ; Update the sum ; Return the sum ; Driver Program | #include <bits/stdc++.h> NEW_LINE using namespace std ; int seriesSum ( int n ) { int sum = 0 ; int currProd = 1 ; int currSum = 1 ; for ( int i = 2 ; i <= n ; i ++ ) { currProd *= i ; currSum += i ; sum += currProd - currSum ; } return sum ; } int main ( ) { int N = 5 ; cout << seriesSum ( N ) << " β " ; } |
Count of elements not divisible by any other elements of Array | C ++ program for the above approach ; Function to count the number of elements of array which are not divisible by any other element in the array arr [ ] ; Iterate over the array ; Check if the element is itself or not ; Check for divisibility ; Return the final result ; Driver Code ; Given array ; Function Call | #include <bits/stdc++.h> NEW_LINE #define ll long long int NEW_LINE using namespace std ; int count ( int a [ ] , int n ) { int countElements = 0 ; for ( int i = 0 ; i < n ; i ++ ) { bool flag = true ; for ( int j = 0 ; j < n ; j ++ ) { if ( i == j ) continue ; if ( a [ i ] % a [ j ] == 0 ) { flag = false ; break ; } } if ( flag == true ) ++ countElements ; } return countElements ; } int main ( ) { int arr [ ] = { 86 , 45 , 18 , 4 , 8 , 28 , 19 , 33 , 2 } ; int n = sizeof ( arr ) / sizeof ( int ) ; cout << count ( arr , n ) ; return 0 ; } |
Smallest N digit number divisible by N | C ++ program for the above approach ; Function to find the smallest N - digit number divisible by N ; Return the smallest N - digit number calculated using above formula ; Driver Code ; Given N ; Function Call | #include <iostream> NEW_LINE #include <math.h> NEW_LINE using namespace std ; int smallestNumber ( int N ) { return N * ceil ( pow ( 10 , ( N - 1 ) ) / N ) ; } int main ( ) { int N = 2 ; cout << smallestNumber ( N ) ; return 0 ; } |
Count pairs in an array containing at least one even value | C ++ implementation to count pairs in an array such that each pair contains at least one even element ; Function to count the pairs in the array such as there is at least one even element in each pair ; Generate all possible pairs and increment then count if the condition is satisfied ; Driver code ; Function call | #include <bits/stdc++.h> NEW_LINE using namespace std ; int CountPairs ( int arr [ ] , int n ) { int count = 0 ; for ( int i = 0 ; i < n ; i ++ ) { for ( int j = i + 1 ; j < n ; j ++ ) { if ( arr [ i ] % 2 == 0 arr [ j ] % 2 == 0 ) count ++ ; } } return count ; } int main ( ) { int arr [ ] = { 8 , 2 , 3 , 1 , 4 , 2 } ; int n = sizeof ( arr ) / sizeof ( int ) ; cout << ( CountPairs ( arr , n ) ) ; } |
Count pairs in an array containing at least one even value | C ++ implementation to Count pairs in an array such that each pair contains at least one even element ; Function to count the pairs in the array such as there is at least one even element in each pair ; Store count of even and odd elements ; Check element is even or odd ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int CountPairs ( int arr [ ] , int n ) { int even = 0 , odd = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( arr [ i ] % 2 == 0 ) even ++ ; else odd ++ ; } return ( even * ( even - 1 ) ) / 2 + ( even * odd ) ; } int main ( ) { int arr [ ] = { 8 , 2 , 3 , 1 , 4 , 2 } ; int n = sizeof ( arr ) / sizeof ( int ) ; cout << CountPairs ( arr , n ) ; } |
Giuga Numbers | C ++ program for the above approach ; Function to check if n is a composite number ; Corner cases ; This is checked to skip middle 5 numbers ; Function to check if N is a Giuga Number ; N should be composite to be a Giuga Number ; Print 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 , print i and divide n ; This condition is to handle the case when n is a prime number > 2 ; Driver Code ; Given Number N ; Function Call | #include <bits/stdc++.h> NEW_LINE using namespace std ; bool isComposite ( int n ) { if ( n <= 1 ) return false ; if ( n <= 3 ) return false ; if ( n % 2 == 0 n % 3 == 0 ) return true ; for ( int i = 5 ; i * i <= n ; i = i + 6 ) if ( n % i == 0 || n % ( i + 2 ) == 0 ) return true ; return false ; } bool isGiugaNum ( int n ) { if ( ! ( isComposite ( n ) ) ) return false ; int N = n ; while ( n % 2 == 0 ) { if ( ( N / 2 - 1 ) % 2 != 0 ) return false ; n = n / 2 ; } for ( int i = 3 ; i <= sqrt ( n ) ; i = i + 2 ) { while ( n % i == 0 ) { if ( ( N / i - 1 ) % i != 0 ) return false ; n = n / i ; } } if ( n > 2 ) if ( ( N / n - 1 ) % n != 0 ) return false ; return true ; } int main ( ) { int N = 30 ; if ( isGiugaNum ( N ) ) cout << " Yes " ; else cout << " No " ; } |
Droll Numbers | C ++ program for the above approach ; Function to check droll numbers ; To store sum of even prime factors ; To store sum of odd prime factors ; Add the number of 2 s that divide n in sum_even ; N must be odd at this point . So we can skip one element ( Note i = i + 2 ) ; While i divides n , print i and divide n ; This condition is to handle the case when n is a prime number greater than 2 ; Condition to check droll number ; Driver Code ; Given Number N ; Function Call | #include <bits/stdc++.h> NEW_LINE using namespace std ; bool isDroll ( int n ) { if ( n == 1 ) return false ; int sum_even = 0 ; int sum_odd = 0 ; while ( n % 2 == 0 ) { sum_even += 2 ; n = n / 2 ; } for ( int i = 3 ; i <= sqrt ( n ) ; i = i + 2 ) { while ( n % i == 0 ) { sum_odd += i ; n = n / i ; } } if ( n > 2 ) sum_odd += n ; return sum_even == sum_odd ; } int main ( ) { int N = 72 ; if ( isDroll ( N ) ) cout << " Yes " ; else cout << " No " ; return 0 ; } |
Count all pairs of divisors of a number N whose sum is coprime with N | C ++ program to count all pairs of divisors such that their sum is coprime with N ; Function to calculate GCD ; Function to count all valid pairs ; Initialize count ; Check if sum of pair and n are coprime ; Return the result ; 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 CountPairs ( int n ) { int cnt = 0 ; for ( int i = 1 ; i * i <= n ; i ++ ) { if ( n % i == 0 ) { int div1 = i ; int div2 = n / i ; int sum = div1 + div2 ; if ( gcd ( sum , n ) == 1 ) cnt += 1 ; } } return cnt ; } int main ( ) { int n = 24 ; cout << CountPairs ( n ) << endl ; return 0 ; } |
Check if A can be converted to B by reducing with a Prime number | C ++ implementation to find if it is possible to make a equal to b ; Function to find if it is possible to make A equal to B ; Driver Code ; Function Call | #include <bits/stdc++.h> NEW_LINE using namespace std ; bool isPossible ( int A , int B ) { return ( A - B > 1 ) ; } int main ( ) { int A = 10 , B = 4 ; if ( isPossible ( A , B ) ) cout << " Yes " ; else cout << " No " ; return 0 ; } |
Maximize sum of minimum difference of divisors of nodes in N | C ++ program to maximize the sum of minimum difference of divisors of nodes in an n - ary tree ; Array to store the result at each node ; Function to get minimum difference between the divisors of a number ; Iterate from square root of N to N ; return absolute difference ; DFS function to calculate the maximum sum ; Store the min difference ; Add the maximum of all children to sub [ u ] ; Return maximum sum of node ' u ' to its parent ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int sub [ 100005 ] ; int minDivisorDifference ( int n ) { int num1 ; int num2 ; for ( int i = sqrt ( n ) ; i <= n ; i ++ ) { if ( n % i == 0 ) { num1 = i ; num2 = n / i ; break ; } } return abs ( num1 - num2 ) ; } int dfs ( vector < int > g [ ] , int u , int par ) { sub [ u ] = minDivisorDifference ( u ) ; int mx = 0 ; for ( auto c : g [ u ] ) { if ( c != par ) { int ans = dfs ( g , c , u ) ; mx = max ( mx , ans ) ; } } sub [ u ] += mx ; return sub [ u ] ; } int main ( ) { vector < int > g [ 100005 ] ; int edges = 6 ; g [ 18 ] . push_back ( 7 ) ; g [ 7 ] . push_back ( 18 ) ; g [ 18 ] . push_back ( 15 ) ; g [ 15 ] . push_back ( 18 ) ; g [ 15 ] . push_back ( 2 ) ; g [ 2 ] . push_back ( 15 ) ; g [ 7 ] . push_back ( 4 ) ; g [ 4 ] . push_back ( 7 ) ; g [ 7 ] . push_back ( 12 ) ; g [ 12 ] . push_back ( 7 ) ; g [ 12 ] . push_back ( 9 ) ; g [ 9 ] . push_back ( 12 ) ; int root = 18 ; cout << dfs ( g , root , -1 ) ; } |
Program to check if N is a Centered Cubic Number | C ++ program to check if N is a centered cubic number ; Function to check if the number N is a centered cubic number ; Iterating from 1 ; Infinite loop ; Finding ith_term ; Checking if the number N is a Centered cube number ; If ith_term > N then N is not a Centered cube number ; Incrementing i ; Driver code ; Function call | #include <bits/stdc++.h> NEW_LINE using namespace std ; bool isCenteredcube ( int N ) { int i = 1 ; while ( true ) { int ith_term = ( 2 * i + 1 ) * ( i * i + i + 1 ) ; if ( ith_term == N ) { return true ; } if ( ith_term > N ) { return false ; } i ++ ; } } int main ( ) { int N = 9 ; if ( isCenteredcube ( N ) ) { cout << " Yes " ; } else { cout << " No " ; } return 0 ; } |
Product of N terms of a given Geometric series | C ++ program for the above approach ; Function to calculate product of geometric series ; Initialise final product with 1 ; Multiply product with each term stored in a ; Return the final product ; Driver Code ; Given first term and common ratio ; Number of terms ; Function Call | #include <bits/stdc++.h> NEW_LINE using namespace std ; float productOfGP ( float a , float r , int n ) { float product = 1 ; for ( int i = 0 ; i < n ; i ++ ) { product = product * a ; a = a * r ; } return product ; } int main ( ) { float a = 1 , r = 2 ; int N = 4 ; cout << productOfGP ( a , r , N ) ; } |
Sum of given N fractions in reduced form | C ++ program for the above approach ; Function to find GCD of a & b using Euclid Lemma ; Base Case ; Function to find the LCM of all elements in arr [ ] ; Initialize result ; Iterate arr [ ] to find LCM ; Return the final LCM ; Function to find the sum of N fraction in reduced form ; To store the sum of all final numerators ; Find the LCM of all denominator ; Find the sum of all N numerators & denominators ; Add each fraction one by one ; Find GCD of final numerator and denominator ; Convert into reduced form by dividing from GCD ; Print the final fraction ; Driven Code ; Given N ; Given Numerator ; Given Denominator ; Function Call | #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 findlcm ( int arr [ ] , int n ) { int ans = arr [ 0 ] ; for ( int i = 1 ; i < n ; i ++ ) { ans = ( ( ( arr [ i ] * ans ) ) / ( gcd ( arr [ i ] , ans ) ) ) ; } return ans ; } void addReduce ( int n , int num [ ] , int den [ ] ) { int final_numerator = 0 ; int final_denominator = findlcm ( den , n ) ; for ( int i = 0 ; i < n ; i ++ ) { final_numerator = final_numerator + ( num [ i ] ) * ( final_denominator / den [ i ] ) ; } int GCD = gcd ( final_numerator , final_denominator ) ; final_numerator /= GCD ; final_denominator /= GCD ; cout << final_numerator << " / " << final_denominator << endl ; } int main ( ) { int N = 3 ; int arr1 [ ] = { 1 , 2 , 5 } ; int arr2 [ ] = { 2 , 1 , 6 } ; addReduce ( N , arr1 , arr2 ) ; return 0 ; } |
Minimum LCM of all pairs in a given array | C ++ program to find minimum possible lcm from any pair ; function to compute GCD of two numbers ; function that return minimum possible lcm from any pair ; fix the ith element and iterate over all the array to find minimum LCM ; 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 minLCM ( int arr [ ] , int n ) { int ans = INT_MAX ; for ( int i = 0 ; i < n ; i ++ ) { for ( int j = i + 1 ; j < n ; j ++ ) { int g = gcd ( arr [ i ] , arr [ j ] ) ; int lcm = arr [ i ] / g * arr [ j ] ; ans = min ( ans , lcm ) ; } } return ans ; } int main ( ) { int arr [ ] = { 2 , 4 , 3 , 6 , 5 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << minLCM ( arr , n ) << endl ; return 0 ; } |
Find two numbers whose difference of fourth power is equal to N | C ++ implementation to find the values of x and y for the given equation with integer N ; Function which find required x & y ; Upper limit of x & y , if such x & y exists ; num1 stores x ^ 4 ; num2 stores y ^ 4 ; If condition is satisfied the print and return ; If no such pair exists ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; void solve ( int n ) { int upper_limit = ceil ( pow ( n , 1.0 / 4 ) ) ; for ( int x = 0 ; x <= upper_limit ; x ++ ) { for ( int y = 0 ; y <= upper_limit ; y ++ ) { int num1 = x * x * x * x ; int num2 = y * y * y * y ; if ( num1 - num2 == n ) { cout << " x β = β " << x << " , β y β = β " << y ; return ; } } } cout << -1 << endl ; } int main ( ) { int n = 15 ; solve ( n ) ; return 0 ; } |
Check if count of even divisors of N is equal to count of odd divisors | C ++ program for the above approach ; Function to check if count of even and odd divisors are equal ; To store the count of even factors and odd factors ; Loop till [ 1 , sqrt ( N ) ] ; If divisors are equal add only one ; Check for even divisor ; Odd divisor ; Check for both divisor i . e . , i and N / i ; Check if i is odd or even ; Check if N / i is odd or even ; Return true if count of even_div and odd_div are equals ; Driver Code ; Given Number ; Function Call | #include <bits/stdc++.h> NEW_LINE using namespace std ; bool divisorsSame ( int n ) { int even_div = 0 , odd_div = 0 ; for ( int i = 1 ; i <= sqrt ( n ) ; i ++ ) { if ( n % i == 0 ) { if ( n / i == i ) { if ( i % 2 == 0 ) { even_div ++ ; } else { odd_div ++ ; } } else { if ( i % 2 == 0 ) { even_div ++ ; } else { odd_div ++ ; } if ( n / i % 2 == 0 ) { even_div ++ ; } else { odd_div ++ ; } } } } return ( even_div == odd_div ) ; } int main ( ) { int N = 6 ; if ( divisorsSame ( N ) ) { cout << " Yes " ; } else { cout << " No " ; } return 0 ; } |
Check if N is a Balanced Prime number or not | C ++ program to check if a given number is Balanced prime ; Utility function to check if a number is prime or not ; Corner cases ; This is checked so that we can skip middle five numbers in below loop ; Function that returns true if n is a Balanced prime ; If n is not a prime number or n is the first prime then return false ; Initialize previous_prime to n - 1 and next_prime to n + 1 ; Find next prime number ; Find previous prime number ; Arithmetic mean ; If n is a weak prime ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; bool isPrime ( int n ) { if ( n <= 1 ) return false ; if ( n <= 3 ) return true ; if ( n % 2 == 0 n % 3 == 0 ) return false ; for ( int i = 5 ; i * i <= n ; i = i + 6 ) if ( n % i == 0 || n % ( i + 2 ) == 0 ) return false ; return true ; } bool isBalancedPrime ( int n ) { if ( ! isPrime ( n ) n == 2 ) return false ; int previous_prime = n - 1 ; int next_prime = n + 1 ; while ( ! isPrime ( next_prime ) ) next_prime ++ ; while ( ! isPrime ( previous_prime ) ) previous_prime -- ; int mean = ( previous_prime + next_prime ) / 2 ; if ( n == mean ) return true ; else return false ; } int main ( ) { int n = 53 ; if ( isBalancedPrime ( n ) ) cout << " Yes " ; else cout << " No " ; return 0 ; } |
Count of nodes having odd divisors in the given subtree for Q queries | C ++ implementation to count the number of nodes having odd number of divisors for each query ; Adjacency list for tree . ; Array for values and answer at ith node . ; Function to check whether N has odd divisors or not ; DFS function to pre - compute the answers ; Initialize the count ; Repeat for every child ; Increase the count if current node has odd number of divisors ; Driver Code ; Adjacency List ; Function call | #include <bits/stdc++.h> NEW_LINE using namespace std ; #define N 100001 NEW_LINE vector < int > adj [ N ] ; int a [ N ] , ans [ N ] ; bool hasOddNumberOfDivisors ( int n ) { if ( ( double ) sqrt ( n ) == ( int ) sqrt ( n ) ) return true ; return false ; } int dfs ( int node , int parent ) { int count = 0 ; for ( auto i = adj [ node ] . begin ( ) ; i != adj [ node ] . end ( ) ; ++ i ) { if ( * i != parent ) { count += dfs ( * i , node ) ; } } if ( hasOddNumberOfDivisors ( a [ node ] ) ) ++ count ; ans [ node ] = count ; return count ; } int main ( ) { int n = 5 , i ; vector < int > q = { 4 , 1 , 5 , 3 } ; adj [ 1 ] . push_back ( 2 ) ; adj [ 2 ] . push_back ( 1 ) ; adj [ 2 ] . push_back ( 3 ) ; adj [ 3 ] . push_back ( 2 ) ; adj [ 3 ] . push_back ( 4 ) ; adj [ 4 ] . push_back ( 3 ) ; adj [ 1 ] . push_back ( 5 ) ; adj [ 5 ] . push_back ( 1 ) ; a [ 1 ] = 4 ; a [ 2 ] = 9 ; a [ 3 ] = 14 ; a [ 4 ] = 100 ; a [ 5 ] = 5 ; dfs ( 1 , -1 ) ; for ( int i = 0 ; i < q . size ( ) ; i ++ ) { cout << ans [ q [ i ] ] << " β " ; } return 0 ; } |
Minimum Cost to make all array elements equal using given operations | C ++ implementation to find the minimum cost to make all array elements equal ; Function that returns the cost of making all elements equal to current element ; Compute the lower bound of current element ; Calculate the requirement of add operation ; Calculate the requirement of subtract operation ; Compute minimum of left and right ; Computing the total cost of add and subtract operations ; Function that prints minimum cost of making all elements equal ; Sort the given array ; Calculate minimum from a + r and m ; Compute prefix sum and store in pref array ; Find the minimum cost from the given elements ; Finding the minimum cost from the other cases where minimum cost can occur ; Printing the minimum cost of making all elements equal ; Driver Code ; Function Call | #include <bits/stdc++.h> NEW_LINE using namespace std ; int costCalculation ( int current , int arr [ ] , int n , int pref [ ] , int a , int r , int minimum ) { int index = lower_bound ( arr , arr + n , current ) - arr ; int left = index * current - pref [ index ] ; int right = pref [ n ] - pref [ index ] - ( n - index ) * current ; int res = min ( left , right ) ; left -= res ; right -= res ; int total = res * minimum ; total += left * a ; total += right * r ; return total ; } void solve ( int arr [ ] , int n , int a , int r , int m ) { sort ( arr , arr + n ) ; int minimum = min ( a + r , m ) ; int pref [ n + 1 ] = { 0 } ; for ( int i = 0 ; i < n ; i ++ ) pref [ i + 1 ] = pref [ i ] + arr [ i ] ; int ans = 10000 ; for ( int i = 0 ; i < n ; i ++ ) ans = min ( ans , costCalculation ( arr [ i ] , arr , n , pref , a , r , minimum ) ) ; ans = min ( ans , costCalculation ( pref [ n ] / n , arr , n , pref , a , r , minimum ) ) ; ans = min ( ans , costCalculation ( pref [ n ] / n + 1 , arr , n , pref , a , r , minimum ) ) ; cout << ans << " STRNEWLINE " ; } int main ( ) { int arr [ ] = { 5 , 5 , 3 , 6 , 5 } ; int A = 1 , R = 2 , M = 4 ; int size = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; solve ( arr , size , A , R , M ) ; return 0 ; } |
Count of integers up to N which represent a Binary number | C ++ Program to count the number of integers upto N which are of the form of binary representations ; Function to return the count ; If the current last digit is 1 ; Add 2 ^ ( ctr - 1 ) possible integers to the answer ; If the current digit exceeds 1 ; Set answer as 2 ^ ctr - 1 as all possible binary integers with ctr number of digits can be obtained ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int countBinaries ( int N ) { int ctr = 1 ; int ans = 0 ; while ( N > 0 ) { if ( N % 10 == 1 ) { ans += pow ( 2 , ctr - 1 ) ; } else if ( N % 10 > 1 ) { ans = pow ( 2 , ctr ) - 1 ; } ctr ++ ; N /= 10 ; } return ans ; } int main ( ) { int N = 20 ; cout << countBinaries ( N ) ; return 0 ; } |
Count of integers up to N which represent a Binary number | C ++ Program to count the number of integers upto N which are of the form of binary representations ; Function to return the count ; PreCompute and store the powers of 2 ; If the current last digit is 1 ; Add 2 ^ ( ctr - 1 ) possible integers to the answer ; If the current digit exceeds 1 ; Set answer as 2 ^ ctr - 1 as all possible binary integers with ctr number of digits can be obtained ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int countBinaries ( int N ) { vector < int > powersOfTwo ( 11 ) ; powersOfTwo [ 0 ] = 1 ; for ( int i = 1 ; i < 11 ; i ++ ) { powersOfTwo [ i ] = powersOfTwo [ i - 1 ] * 2 ; } int ctr = 1 ; int ans = 0 ; while ( N > 0 ) { if ( N % 10 == 1 ) { ans += powersOfTwo [ ctr - 1 ] ; } else if ( N % 10 > 1 ) { ans = powersOfTwo [ ctr ] - 1 ; } ctr ++ ; N /= 10 ; } return ans ; } int main ( ) { int N = 20 ; cout << countBinaries ( N ) ; return 0 ; } |
Find the sum of the first Nth Centered Hexadecagonal Number | C ++ program to find the sum of the first N centred hexadecagonal numbers ; Centered_Hexadecagonal number function ; Formula to calculate nth Centered_Hexadecagonal number & return it into main function . ; Function to find the sum of the first N centered hexadecagonal number ; Variable to store the sum ; Loop to iterate through the first N numbers ; Finding the sum ; Driver code ; Display first Nth Centered_Hexadecagonal number | #include <bits/stdc++.h> NEW_LINE using namespace std ; int Centered_Hexadecagonal_num ( int n ) { return ( 8 * n * n - 8 * n + 1 ) ; } int sum_Centered_Hexadecagonal_num ( int n ) { int summ = 0 ; for ( int i = 1 ; i < n + 1 ; i ++ ) { summ += Centered_Hexadecagonal_num ( i ) ; } return summ ; } int main ( ) { int n = 5 ; cout << sum_Centered_Hexadecagonal_num ( n ) ; } |
Find the sum of the first N Centered heptagonal number | C ++ program to find the sum of the first N centered heptagonal numbers ; Function to find the N - th centered heptagonal number ; Formula to calculate nth centered heptagonal number ; Function to find the sum of the first N centered heptagonal numbers ; Variable to store the sum ; Iterating through the range 1 to N ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int center_heptagonal_num ( int n ) { return ( 7 * n * n - 7 * n + 2 ) / 2 ; } int sum_center_heptagonal_num ( int n ) { int summ = 0 ; for ( int i = 1 ; i < n + 1 ; i ++ ) { summ += center_heptagonal_num ( i ) ; } return summ ; } int main ( ) { int n = 5 ; cout << ( sum_center_heptagonal_num ( n ) ) ; return 0 ; } |
Find the sum of the first N Centered Dodecagonal Number | C ++ program to find the sum of the first N Centred Dodecagonal number ; Function to find the N - th Centered Dodecagonal number ; Formula to calculate nth Centered_Dodecagonal number ; Function to find the sum of the first N Centered_Dodecagonal number ; Variable to store the sum ; Iterating from 1 to N ; Finding the sum ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int Centered_Dodecagonal_num ( int n ) { return 6 * n * ( n - 1 ) + 1 ; } int sum_Centered_Dodecagonal_num ( int n ) { int summ = 0 ; for ( int i = 1 ; i < n + 1 ; i ++ ) { summ += Centered_Dodecagonal_num ( i ) ; } return summ ; } int main ( ) { int n = 5 ; cout << sum_Centered_Dodecagonal_num ( n ) ; } |
Find the sum of the first N Centered Octagonal Number | C ++ program to find the sum of the first N centered octagonal number ; Function to find the N - th centered octagonal number ; Formula to calculate nth centered octagonal number ; Function to find the sum of the first N centered octagonal numbers ; Variable to store the sum ; Iterating through the range 1 to N ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int center_Octagonal_num ( int n ) { return ( 4 * n * n - 4 * n + 1 ) ; } int sum_center_Octagonal_num ( int n ) { int summ = 0 ; for ( int i = 1 ; i < n + 1 ; i ++ ) { summ += center_Octagonal_num ( i ) ; } return summ ; } int main ( ) { int n = 5 ; cout << ( sum_center_Octagonal_num ( n ) ) ; return 0 ; } |
Find the sum of the first N Centered Decagonal Numbers | C ++ program to find the sum of the first N centred decagonal number ; Function to find the N - th centred decagonal number ; Formula to calculate nth centered_decagonal number & return it into main function . ; Function to find the sum of the first N centered decagonal numbers ; Variable to store the sum ; Iterating through the range ; Driver code ; Display first Nth centered_decagonal number | #include <bits/stdc++.h> NEW_LINE using namespace std ; int Centered_decagonal_num ( int n ) { return ( 5 * n * n - 5 * n + 1 ) ; } int sum_Centered_decagonal_num ( int n ) { int summ = 0 ; for ( int i = 1 ; i < n + 1 ; i ++ ) { summ += Centered_decagonal_num ( i ) ; } return summ ; } int main ( ) { int n = 5 ; cout << ( sum_Centered_decagonal_num ( n ) ) ; return 0 ; } |
Find the sum of the first N Centered Octadecagonal Numbers | C ++ program to find the sum of the first N centered octadecagonal numbers ; Function to find the N - th centered octadecagonal number ; Formula to calculate nth centered octadecagonal number ; Function to find the sum of the first N centered octadecagonal numbers ; Variable to store the sum ; Iterating through the range 1 to N ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int center_octadecagon_num ( int n ) { return ( 9 * n * n - 9 * n + 1 ) ; } int sum_center_octadecagon_num ( int n ) { int summ = 0 ; for ( int i = 1 ; i < n + 1 ; i ++ ) { summ += center_octadecagon_num ( i ) ; } return summ ; } int main ( ) { int n = 3 ; cout << ( sum_center_octadecagon_num ( n ) ) ; return 0 ; } |
Find the sum of the first Nth Centered Pentadecagonal Number | C ++ program to find the sum of the first N centered pentadecagonal number ; Function to find the centered pentadecagonal number ; Formula to calculate N - th centered pentadecagonal number ; Function to find the sum of the first N centered pentadecagonal numbers ; Variable to store the sum ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int Centered_Pentadecagonal_num ( int n ) { return ( 15 * n * n - 15 * n + 2 ) / 2 ; } int sum_Centered_Pentadecagonal_num ( int n ) { int summ = 0 ; for ( int i = 1 ; i < n + 1 ; i ++ ) { summ += Centered_Pentadecagonal_num ( i ) ; } return summ ; } int main ( ) { int n = 5 ; cout << sum_Centered_Pentadecagonal_num ( n ) ; return 0 ; } |
Program to check if N is a Octagonal Number | C ++ program for the above approach ; Function to check if N is a Octagonal Number ; Condition to check if the number is a octagonal number ; Driver Code ; Given Number ; Function call | #include <bits/stdc++.h> NEW_LINE using namespace std ; bool isoctagonal ( int N ) { float n = ( 2 + sqrt ( 12 * N + 4 ) ) / 6 ; return ( n - ( int ) n ) == 0 ; } int main ( ) { int N = 8 ; if ( isoctagonal ( N ) ) { cout << " Yes " ; } else { cout << " No " ; } return 0 ; } |
Program to check if N is a Pentadecagonal Number | C ++ program for the above approach ; Function to check if N is a Pentadecagon number ; Condition to check if the number is a Pentadecagon number ; Driver Code ; Given Number ; Function call | #include <bits/stdc++.h> NEW_LINE using namespace std ; bool isPentadecagon ( int N ) { float n = ( 11 + sqrt ( 104 * N + 121 ) ) / 26 ; return ( n - ( int ) n ) == 0 ; } int main ( ) { int N = 15 ; if ( isPentadecagon ( N ) ) { cout << " Yes " ; } else { cout << " No " ; } return 0 ; } |
Program to check if N is a Tetradecagonal Number | C ++ program for the above approach ; Function to check if N is a Tetradecagonal Number ; Condition to check if the number is a tetradecagonal number ; Driver Code ; Given Number ; Function call | #include <bits/stdc++.h> NEW_LINE using namespace std ; bool istetradecagonal ( int N ) { float n = ( 10 + sqrt ( 96 * N + 100 ) ) / 24 ; return ( n - ( int ) n ) == 0 ; } int main ( ) { int N = 11 ; if ( istetradecagonal ( N ) ) { cout << " Yes " ; } else { cout << " No " ; } return 0 ; } |
Find the sum of the first Nth Icosagonal Numbers | C ++ program to find the sum of the first N icosagonal number ; Function to calculate the N - th icosagonal number ; Formula to calculate nth icosagonal number & return it ; Function to find the sum of the first N icosagonal numbers ; Variable to store the sum ; Loop to iterate through the first N values and find the sum of first N icosagonal numbers ; Function to get the Icosagonal_num ; Driver code ; Display the sum of first N icosagonal number | #include <bits/stdc++.h> NEW_LINE using namespace std ; int Icosagonal_num ( int n ) { return ( 18 * n * n - 16 * n ) / 2 ; } int sum_Icosagonal_num ( int n ) { int summ = 0 ; for ( int i = 1 ; i <= n ; i ++ ) { summ += Icosagonal_num ( i ) ; } return summ ; } int main ( ) { int n = 5 ; cout << sum_Icosagonal_num ( n ) << endl ; } |
Find the sum of the first N Centered Pentagonal Number | C ++ program to find the sum of the first N centered pentagonal numbers ; Function to find the Centered_Pentagonal number ; Formula to calculate nth Centered_Pentagonal number & return it into main function . ; Function to find the sum of the first N Centered_Pentagonal numbers ; To get the sum ; Iterating through the range 1 to N ; Driver Code ; Display first Nth Centered_Pentagonal number | #include <bits/stdc++.h> NEW_LINE using namespace std ; int Centered_Pentagonal_num ( int n ) { return ( 5 * n * n - 5 * n + 2 ) / 2 ; } int sum_Centered_Pentagonal_num ( int n ) { int summ = 0 ; for ( int i = 1 ; i < n + 1 ; i ++ ) { summ += Centered_Pentagonal_num ( i ) ; } return summ ; } int main ( ) { int n = 5 ; cout << ( sum_Centered_Pentagonal_num ( n ) ) ; return 0 ; } |
Find the sum of the first Nth Centered Tridecagonal Numbers | C ++ program to find the sum of the first Nth centered tridecagonal number ; Function to calculate the N - th centered tridecagonal number ; Formula to calculate Nth centered tridecagonal number & return it ; Function to find the sum of the first N centered tridecagonal numbers ; Variable to store the sum ; Loop to iterate and find the sum of first N centered tridecagonal numbers ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int Centered_tridecagonal_num ( int n ) { return ( 13 * n * ( n - 1 ) + 2 ) / 2 ; } int sum_Centered_tridecagonal_num ( int n ) { int summ = 0 ; for ( int i = 1 ; i <= n ; i ++ ) { summ += Centered_tridecagonal_num ( i ) ; } return summ ; } int main ( ) { int n = 5 ; cout << sum_Centered_tridecagonal_num ( n ) << endl ; return 0 ; } |
Program to check if N is a Concentric Hexagonal Number | C ++ program to check if N is a Concentric Hexagonal Number ; Function to check if the number is a Concentric hexagonal number ; Condition to check if the number is a Concentric hexagonal number ; Driver Code ; Function call | #include <bits/stdc++.h> NEW_LINE using namespace std ; bool isConcentrichexagonal ( int N ) { float n = sqrt ( ( 2 * N ) / 3 ) ; return ( n - ( int ) n ) == 0 ; } int main ( ) { int N = 6 ; if ( isConcentrichexagonal ( N ) ) { cout << " Yes " ; } else { cout << " No " ; } return 0 ; } |
Count Sexy Prime Pairs in the given array | C ++ program to count Sexy Prime pairs in array ; To store check the prime number ; A utility function that find the Prime Numbers till N ; Resize the Prime Number ; Loop till sqrt ( N ) to find prime numbers and make their multiple false in the bool array Prime ; Function that returns the count of SPP ( Sexy Prime Pair ) Pairs ; Find the maximum element in the given array arr [ ] ; Function to calculate the prime numbers till N ; To store the count of pairs ; To store the frequency of element in the array arr [ ] ; Sort before traversing the array ; Traverse the array and find the pairs with SPP ( Sexy Prime Pair ) ; If current element is Prime , then check for ( current element + 6 ) ; Return the count of pairs ; Driver code ; Function call to find SPP ( Sexy Prime Pair ) pair | #include <bits/stdc++.h> NEW_LINE using namespace std ; vector < bool > Prime ; void computePrime ( int N ) { Prime . resize ( N + 1 , true ) ; Prime [ 0 ] = Prime [ 1 ] = false ; for ( int i = 2 ; i * i <= N ; i ++ ) { if ( Prime [ i ] ) { for ( int j = i * i ; j < N ; j += i ) { Prime [ j ] = false ; } } } } int countSexyPairs ( int arr [ ] , int n ) { int maxE = * max_element ( arr , arr + n ) ; computePrime ( maxE ) ; int count = 0 ; int freq [ maxE + 1 ] = { 0 } ; for ( int i = 0 ; i < n ; i ++ ) { freq [ arr [ i ] ] ++ ; } sort ( arr , arr + n ) ; for ( int i = 0 ; i < n ; i ++ ) { if ( Prime [ arr [ i ] ] ) { if ( freq [ arr [ i ] + 6 ] > 0 && Prime [ arr [ i ] + 6 ] ) { count ++ ; } } } return count ; } int main ( ) { int arr [ ] = { 6 , 7 , 5 , 11 , 13 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << countSexyPairs ( arr , n ) ; return 0 ; } |
Count of ways to write N as a sum of three numbers | C ++ program to count the total number of ways to write N as a sum of three numbers ; Function to find the number of ways ; Check if number is less than 2 ; Calculate the sum ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; void countWays ( int n ) { if ( n <= 2 ) cout << " - 1" ; else { int ans = ( n - 1 ) * ( n - 2 ) / 2 ; cout << ans ; } } int main ( ) { int N = 5 ; countWays ( N ) ; return 0 ; } |
Logarithm tricks for Competitive Programming | C ++ implementation to check that a integer is a power of Two ; Function to check if the number is a power of two ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; bool isPowerOfTwo ( int n ) { return ( ceil ( log2 ( n ) ) == floor ( log2 ( n ) ) ) ; } int main ( ) { int N = 8 ; if ( isPowerOfTwo ( N ) ) { cout << " Yes " ; } else { cout << " No " ; } } |
Count of pairs having bit size at most X and Bitwise OR equal to X | C ++ implementation to Count number of possible pairs of ( a , b ) such that their Bitwise OR gives the value X ; Function to count the pairs ; Initializing answer with 1 ; Iterating through bits of x ; check if bit is 1 ; multiplying ans by 3 if bit is 1 ; Driver code | #include <iostream> NEW_LINE using namespace std ; int count_pairs ( int x ) { int ans = 1 ; while ( x > 0 ) { if ( x % 2 == 1 ) ans = ans * 3 ; x = x / 2 ; } return ans ; } int main ( ) { int X = 6 ; cout << count_pairs ( X ) << endl ; return 0 ; } |
Find the Kth number which is not divisible by N | C ++ implementation for above approach ; Function to find the Kth not divisible by N ; Lowest possible value ; Highest possible value ; To store the Kth non divisible number of N ; Using binary search ; Calculating mid value ; Sol would have the value by subtracting all multiples of n till mid ; Check if sol is greater than k ; H should be reduced to find minimum possible value ; Check if sol is less than k then L will be mid + 1 ; Check if sol is equal to k ; ans will be mid ; H would be reduced to find any more possible value ; Print the answer ; Driver Code ; Function Call | #include <bits/stdc++.h> NEW_LINE using namespace std ; void kthNonDivisible ( int N , int K ) { int L = 1 ; int H = INT_MAX ; int ans = 0 ; while ( L <= H ) { int mid = ( L + H ) / 2 ; int sol = mid - mid / N ; if ( sol > K ) { H = mid - 1 ; } else if ( sol < K ) { L = mid + 1 ; } else { ans = mid ; H = mid - 1 ; } } cout << ans ; } int main ( ) { int N = 3 ; int K = 7 ; kthNonDivisible ( N , K ) ; return 0 ; } |
Print any pair of integers with sum of GCD and LCM equals to N | C ++ implementation to Print any pair of integers whose summation of GCD and LCM is equal to integer N ; Function to print the required pair ; print the pair ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; void printPair ( int n ) { cout << 1 << " β " << n - 1 ; } int main ( ) { int n = 14 ; printPair ( n ) ; return 0 ; } |
Find the length of largest subarray in which all elements are Autobiographical Numbers | C ++ program to find the length of the largest subarray whose every element is an Autobiographical Number ; function to check number is autobiographical ; Convert integer to string ; Iterate for every digit to check for their total count ; Check occurrence of every number and count them ; Check if any position mismatches with total count them return with false else continue with loop ; Function to return the length of the largest subarray whose every element is a Autobiographical number ; Utility function which checks every element of array for Autobiographical number ; Check if element arr [ i ] is an Autobiographical number ; Increment the current length ; Update max_length value ; Return the final result ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; bool isAutoBiographyNum ( int number ) { int count = 0 , position , size , digit ; string NUM ; NUM = to_string ( number ) ; size = NUM . length ( ) ; for ( int i = 0 ; i < size ; i ++ ) { position = NUM [ i ] - '0' ; count = 0 ; for ( int j = 0 ; j < size ; j ++ ) { digit = NUM [ j ] - '0' ; if ( digit == i ) count ++ ; } if ( position != count ) return false ; } return true ; } int checkArray ( int arr [ ] , int n ) { int current_length = 0 ; int max_length = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( isAutoBiographyNum ( arr [ i ] ) ) current_length ++ ; else current_length = 0 ; max_length = max ( max_length , current_length ) ; } return max_length ; } int main ( ) { int arr [ ] = { 21200 , 1 , 1303 , 1210 , 2020 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << checkArray ( arr , n ) << " STRNEWLINE " ; return 0 ; } |
Euler 's Factorization method | C ++ program to implement Eulers Factorization algorithm ; Function to return N as the sum of two squares in two possible ways ; Iterate a loop from 1 to sqrt ( n ) ; If i * i is square check if there exists another integer such that h is a perfect square and i * i + h = n ; If h is perfect square ; Store in the sorted way ; If there is already a pair check if pairs are equal or not ; Insert the first pair ; If two pairs are found ; Function to find the factors ; Get pairs where a ^ 2 + b ^ 2 = n ; Number cannot be represented as sum of squares in two ways ; Assign a , b , c , d ; Swap if a < c because if a - c < 0 , GCD cant be computed . ; Compute the values of k , h , l , m using the formula mentioned in the approach ; Print the values of a , b , c , d and k , l , m , h ; Printing the factors ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; void sumOfSquares ( int n , vector < pair < int , int > > & vp ) { for ( int i = 1 ; i <= sqrt ( n ) ; i ++ ) { int h = n - i * i , h1 = sqrt ( h ) ; if ( h1 * h1 == h ) { int a = max ( h1 , i ) , b = min ( h1 , i ) ; if ( vp . size ( ) == 1 && a != vp [ 0 ] . first ) vp . push_back ( make_pair ( a , b ) ) ; if ( vp . size ( ) == 0 ) vp . push_back ( make_pair ( a , b ) ) ; if ( vp . size ( ) == 2 ) return ; } } } void findFactors ( int n ) { vector < pair < int , int > > vp ; sumOfSquares ( n , vp ) ; if ( vp . size ( ) != 2 ) cout << " Factors β Not β Possible " ; int a , b , c , d ; a = vp [ 0 ] . first ; b = vp [ 0 ] . second ; c = vp [ 1 ] . first ; d = vp [ 1 ] . second ; if ( a < c ) { int t = a ; a = c ; c = t ; t = b ; b = d ; d = t ; } int k , h , l , m ; k = __gcd ( a - c , d - b ) ; h = __gcd ( a + c , d + b ) ; l = ( a - c ) / k ; m = ( d - b ) / k ; cout << " a β = β " << a << " TABSYMBOL TABSYMBOL ( A ) β a β - β c β = β " << ( a - c ) << " TABSYMBOL TABSYMBOL k β = β gcd [ A , β C ] β = β " << k << endl ; cout << " b β = β " << b << " TABSYMBOL TABSYMBOL ( B ) β a β + β c β = β " << ( a + c ) << " TABSYMBOL TABSYMBOL h β = β gcd [ B , β D ] β = β " << h << endl ; cout << " c β = β " << c << " TABSYMBOL TABSYMBOL ( C ) β d β - β b β = β " << ( d - b ) << " TABSYMBOL TABSYMBOL l β = β A / k β = β " << l << endl ; cout << " d β = β " << d << " TABSYMBOL TABSYMBOL ( D ) β d β + β b β = β " << ( d + b ) << " TABSYMBOL TABSYMBOL m β = β c / k β = β " << m << endl ; if ( k % 2 == 0 && h % 2 == 0 ) { k = k / 2 ; h = h / 2 ; cout << " Factors β are : β " << ( ( k ) * ( k ) + ( h ) * ( h ) ) << " β " << ( l * l + m * m ) << endl ; } else { l = l / 2 ; m = m / 2 ; cout << " Factors β are : β " << ( ( l ) * ( l ) + ( m ) * ( m ) ) << " β " << ( k * k + h * h ) << endl ; } } int main ( ) { int n = 100000 ; findFactors ( n ) ; return 0 ; } |
Print the nodes of the Binary Tree whose height is a Prime number | C ++ implementation of nodes at prime height in the given tree ; To store Prime Numbers ; To store height of each node ; Function to find the prime numbers till 10 ^ 5 ; Traverse all multiple of i and make it false ; Function to perform dfs ; Store the height of node ; Function to find the nodes at prime height ; To precompute prime number till 10 ^ 5 ; Check if height [ node ] is prime ; Driver code ; Number of nodes ; Edges of the tree | #include <bits/stdc++.h> NEW_LINE using namespace std ; #define MAX 100000 NEW_LINE vector < int > graph [ MAX + 1 ] ; vector < bool > Prime ( MAX + 1 , true ) ; int height [ MAX + 1 ] ; void SieveOfEratosthenes ( ) { int i , j ; Prime [ 0 ] = Prime [ 1 ] = false ; for ( i = 2 ; i * i <= MAX ; i ++ ) { if ( Prime [ i ] ) { for ( j = 2 * i ; j < MAX ; j += i ) { Prime [ j ] = false ; } } } } void dfs ( int node , int parent , int h ) { height [ node ] = h ; for ( int to : graph [ node ] ) { if ( to == parent ) continue ; dfs ( to , node , h + 1 ) ; } } void primeHeightNode ( int N ) { SieveOfEratosthenes ( ) ; for ( int i = 1 ; i <= N ; i ++ ) { if ( Prime [ height [ i ] ] ) { cout << i << " β " ; } } } int main ( ) { int N = 5 ; graph [ 1 ] . push_back ( 2 ) ; graph [ 1 ] . push_back ( 3 ) ; graph [ 2 ] . push_back ( 4 ) ; graph [ 2 ] . push_back ( 5 ) ; dfs ( 1 , 1 , 0 ) ; primeHeightNode ( N ) ; return 0 ; } |
Find Prime Adam integers in the given range [ L , R ] | C ++ program to find all prime adam numbers in the given range ; Reversing a number by taking remainder at a time ; Function to check if a number is a prime or not ; Iterating till the number ; Checking for factors ; Returning 1 if the there are no factors of the number other than 1 or itself ; Function to check whether a number is an adam number or not ; Reversing given number ; Squaring given number ; Squaring reversed number ; Reversing the square of the reversed number ; Checking if the square of the number and the square of its reverse are equal or not ; Function to find all the prime adam numbers in the given range ; If the first number is greater than the second number , print invalid ; Iterating through all the numbers in the given range ; Checking for prime number ; Checking for Adam number ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int reverse ( int a ) { int rev = 0 ; while ( a != 0 ) { int r = a % 10 ; rev = rev * 10 + r ; a = a / 10 ; } return ( rev ) ; } int prime ( int a ) { int k = 0 ; for ( int i = 2 ; i < a ; i ++ ) { if ( a % i == 0 ) { k = 1 ; break ; } } if ( k == 1 ) { return ( 0 ) ; } else { return ( 1 ) ; } } int adam ( int a ) { int r1 = reverse ( a ) ; int s1 = a * a ; int s2 = r1 * r1 ; int r2 = reverse ( s2 ) ; if ( s1 == r2 ) { return ( 1 ) ; } else { return ( 0 ) ; } } void find ( int m , int n ) { if ( m > n ) { cout << " β INVALID β INPUT β " << endl ; } else { int c = 0 ; for ( int i = m ; i <= n ; i ++ ) { int l = prime ( i ) ; int k = adam ( i ) ; if ( ( l == 1 ) && ( k == 1 ) ) { cout << i << " TABSYMBOL " ; } } } } int main ( ) { int L = 5 , R = 100 ; find ( L , R ) ; return 0 ; } |
Determine whether the given integer N is a Peculiar Number or not | C ++ implementation to check if the number is peculiar ; Function to find sum of digits of a number ; Function to check if the number is peculiar ; Store a duplicate of n ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int sumDig ( int n ) { int s = 0 ; while ( n != 0 ) { s = s + ( n % 10 ) ; n = n / 10 ; } return s ; } bool Pec ( int n ) { int dup = n ; int dig = sumDig ( n ) ; if ( dig * 3 == dup ) return true ; else return false ; } int main ( ) { int n = 36 ; if ( Pec ( n ) == true ) cout << " Yes " << endl ; else cout << " No " << endl ; return 0 ; } |
Find N numbers such that a number and its reverse are divisible by sum of its digits | C ++ program to print the first N numbers such that every number and the reverse of the number is divisible by its sum of digits ; Function to calculate the sum of digits ; Loop to iterate through every digit of the number ; Returning the sum of digits ; Function to calculate the reverse of a number ; Loop to calculate the reverse of the number ; Return the reverse of the number ; Function to print the first N numbers such that every number and the reverse of the number is divisible by its sum of digits ; Loop to continuously check and generate number until there are n outputs ; Variable to hold the sum of the digit of the number ; Computing the reverse of the number ; Checking if the condition satisfies . Increment the count and print the number if it satisfies . ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int digit_sum ( int n ) { int sum = 0 , m ; while ( n > 0 ) { m = n % 10 ; sum = sum + m ; n = n / 10 ; } return ( sum ) ; } int reverse ( int n ) { int r = 0 ; while ( n != 0 ) { r = r * 10 ; r = r + n % 10 ; n = n / 10 ; } return ( r ) ; } void operation ( int n ) { int i = 1 , a , count = 0 , r ; while ( count < n ) { a = digit_sum ( i ) ; r = reverse ( i ) ; if ( i % a == 0 && r % a == 0 ) { cout << i << " β " ; count ++ ; i ++ ; } else i ++ ; } } int main ( ) { int n = 10 ; operation ( n ) ; } |
Split N natural numbers into two sets having GCD of their sums greater than 1 | C ++ program to split N natural numbers into two sets having GCD of their sums greater than 1 ; Function to create and print the two sets ; No such split possible for N <= 2 ; Print the first set consisting of even elements ; Print the second set consisting of odd ones ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; void createSets ( int N ) { if ( N <= 2 ) { cout << " - 1" << endl ; return ; } for ( int i = 2 ; i <= N ; i += 2 ) cout << i << " β " ; cout << " STRNEWLINE " ; for ( int i = 1 ; i <= N ; i += 2 ) { cout << i << " β " ; } } int main ( ) { int N = 6 ; createSets ( N ) ; return 0 ; } |
Count the nodes in the given tree whose weight is a powerful number | C ++ implementation to Count the nodes in the given tree whose weight is a powerful number ; Function to check if the number is powerful ; First divide the number repeatedly by 2 ; Check if only 2 ^ 1 divides n , then return false ; Check if n is not a power of 2 then this loop will execute ; Find highest power of " factor " that divides n ; Check if only factor ^ 1 divides n , then return false ; n must be 1 now if it is not a prime number . Since prime numbers are not powerful , we return false if n is not 1. ; Function to perform dfs ; Check if weight of the current node is a powerful number ; Driver code ; Weights of the node ; Edges of the tree | #include <bits/stdc++.h> NEW_LINE using namespace std ; int ans = 0 ; vector < int > graph [ 100 ] ; vector < int > weight ( 100 ) ; bool isPowerful ( int n ) { while ( n % 2 == 0 ) { int power = 0 ; while ( n % 2 == 0 ) { n /= 2 ; power ++ ; } if ( power == 1 ) return false ; } for ( int factor = 3 ; factor <= sqrt ( n ) ; factor += 2 ) { int power = 0 ; while ( n % factor == 0 ) { n = n / factor ; power ++ ; } if ( power == 1 ) return false ; } return ( n == 1 ) ; } void dfs ( int node , int parent ) { if ( isPowerful ( weight [ node ] ) ) ans += 1 ; for ( int to : graph [ node ] ) { if ( to == parent ) continue ; dfs ( to , node ) ; } } int main ( ) { weight [ 1 ] = 5 ; weight [ 2 ] = 10 ; weight [ 3 ] = 11 ; weight [ 4 ] = 8 ; weight [ 5 ] = 6 ; graph [ 1 ] . push_back ( 2 ) ; graph [ 2 ] . push_back ( 3 ) ; graph [ 2 ] . push_back ( 4 ) ; graph [ 1 ] . push_back ( 5 ) ; dfs ( 1 , 1 ) ; cout << ans ; return 0 ; } |
Number of ways to color boundary of each block of M * N table | C ++ program to count the number of ways to color boundary of each block of M * N table . ; Function to compute all way to fill the boundary of all sides of the unit square ; Count possible ways to fill all upper and left side of the rectangle M * N ; Count possible ways to fill all side of the all squares unit size ; Driver code ; Number of rows ; Number of columns | #include <bits/stdc++.h> NEW_LINE using namespace std ; int CountWays ( int N , int M ) { int count = 1 ; count = pow ( 3 , M + N ) ; count *= pow ( 2 , M * N ) ; return count ; } int main ( ) { int N = 3 ; int M = 2 ; cout << CountWays ( N , M ) ; return 0 ; } |
Nth positive number whose absolute difference of adjacent digits is at most 1 | C ++ Program to find Nth number with absolute difference between all adjacent digits at most 1. ; Return Nth number with absolute difference between all adjacent digits at most 1. ; To store all such numbers ; Enqueue all integers from 1 to 9 in increasing order . ; Perform the operation N times so that we can get all such N numbers . ; Store the front element of queue , in array and pop it from queue . ; If the last digit of dequeued integer is not 0 , then enqueue the next such number . ; Enqueue the next such number ; If the last digit of dequeued integer is not 9 , then enqueue the next such number . ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; void findNthNumber ( int N ) { long long arr [ N + 1 ] ; queue < long long > q ; for ( int i = 1 ; i <= 9 ; i ++ ) q . push ( i ) ; for ( int i = 1 ; i <= N ; i ++ ) { arr [ i ] = q . front ( ) ; q . pop ( ) ; if ( arr [ i ] % 10 != 0 ) q . push ( arr [ i ] * 10 + arr [ i ] % 10 - 1 ) ; q . push ( arr [ i ] * 10 + arr [ i ] % 10 ) ; if ( arr [ i ] % 10 != 9 ) q . push ( arr [ i ] * 10 + arr [ i ] % 10 + 1 ) ; } cout << arr [ N ] << endl ; } int main ( ) { int N = 21 ; findNthNumber ( N ) ; return 0 ; } |
Unique element in an array where all elements occur K times except one | Set 2 | C ++ program for the above approach ; Function that find the unique element in the array arr [ ] ; Store all unique element in set ; Sum of all element of the array ; Sum of element in the set ; Print the unique element using formula ; Driver Code ; Function call | #include <bits/stdc++.h> NEW_LINE using namespace std ; int findUniqueElements ( int arr [ ] , int N , int K ) { unordered_set < int > s ( arr , arr + N ) ; int arr_sum = accumulate ( arr , arr + N , 0 ) ; int set_sum = accumulate ( s . begin ( ) , s . end ( ) , 0 ) ; cout << ( K * set_sum - arr_sum ) / ( K - 1 ) ; } int main ( ) { int arr [ ] = { 12 , 1 , 12 , 3 , 12 , 1 , 1 , 2 , 3 , 2 , 2 , 3 , 7 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; int K = 3 ; findUniqueElements ( arr , N , K ) ; return 0 ; } |
Form the Cubic equation from the given roots | C ++ program for the approach ; Function to find the cubic equation whose roots are a , b and c ; Find the value of coefficient ; Print the equation as per the above coefficients ; Driver Code ; Function Call | #include <bits/stdc++.h> NEW_LINE using namespace std ; void findEquation ( int a , int b , int c ) { int X = ( a + b + c ) ; int Y = ( a * b ) + ( b * c ) + ( c * a ) ; int Z = a * b * c ; cout << " x ^ 3 β - β " << X << " x ^ 2 β + β " << Y << " x β - β " << Z << " β = β 0" ; } int main ( ) { int a = 5 , b = 2 , c = 3 ; findEquation ( a , b , c ) ; return 0 ; } |
Gill 's 4th Order Method to solve Differential Equations | C ++ program to implement Gill 's method ; A sample differential equation " dy / dx β = β ( x β - β y ) /2" ; Finds value of y for a given x using step size h and initial value y0 at x0 ; Count number of iterations using step size or height h ; Value of K_i ; Initial value of y ( 0 ) ; Iterate for number of iteration ; Value of K1 ; Value of K2 ; Value of K3 ; Value of K4 ; Find the next value of y ( n + 1 ) using y ( n ) and values of K in the above steps ; Update next value of x ; Return the final value of dy / dx ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; float dydx ( float x , float y ) { return ( x - y ) / 2 ; } float Gill ( float x0 , float y0 , float x , float h ) { int n = ( int ) ( ( x - x0 ) / h ) ; float k1 , k2 , k3 , k4 ; float y = y0 ; for ( int i = 1 ; i <= n ; i ++ ) { k1 = h * dydx ( x0 , y ) ; k2 = h * dydx ( x0 + 0.5 * h , y + 0.5 * k1 ) ; k3 = h * dydx ( x0 + 0.5 * h , y + 0.5 * ( -1 + sqrt ( 2 ) ) * k1 + k2 * ( 1 - 0.5 * sqrt ( 2 ) ) ) ; k4 = h * dydx ( x0 + h , y - ( 0.5 * sqrt ( 2 ) ) * k2 + k3 * ( 1 + 0.5 * sqrt ( 2 ) ) ) ; y = y + ( 1.0 / 6 ) * ( k1 + ( 2 - sqrt ( 2 ) ) * k2 + ( 2 + sqrt ( 2 ) ) * k3 + k4 ) ; x0 = x0 + h ; } return y ; } int main ( ) { float x0 = 0 , y = 3.0 , x = 5.0 , h = 0.2 ; printf ( " y ( x ) β = β % .6f " , Gill ( x0 , y , x , h ) ) ; return 0 ; } |
Program to print numbers from N to 1 in reverse order | C ++ program to print all numbers between 1 to N in reverse order ; Recursive function to print from N to 1 ; Driven Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; void PrintReverseOrder ( int N ) { for ( int i = N ; i > 0 ; i -- ) cout << i << " β " ; } int main ( ) { int N = 5 ; PrintReverseOrder ( N ) ; return 0 ; } |
XLCost for text-to-code synthesis
Dataset Description
This is a subset of XLCoST benchmark, for text-to-code generation at snippet level and program level for 7 programming languages: Python, C, C#, C++, Java, Javascript and PHP
.
Languages
The dataset contains text in English and its corresponding code translation. Each program is divided into several code snippets, so the snipppet-level subsets contain these code snippets with their corresponding comments, for program-level subsets, the comments were concatenated in one long description. Moreover, programs in all the languages are aligned at the snippet level and the comment for a particular snippet is the same across all the languages.
Dataset Structure
To load the dataset you need to specify a subset among the 14 exiting instances: LANGUAGE-snippet-level/LANGUAGE-program-level
for LANGUAGE
in [Python, C, Csharp, C++, Java, Javascript and PHP]
. By default Python-snippet-level
is loaded.
from datasets import load_dataset
load_dataset("codeparrot/xlcost-text-to-code", "Python-program-level")
DatasetDict({
train: Dataset({
features: ['text', 'code'],
num_rows: 9263
})
test: Dataset({
features: ['text', 'code'],
num_rows: 887
})
validation: Dataset({
features: ['text', 'code'],
num_rows: 472
})
})
next(iter(data["train"]))
{'text': 'Maximum Prefix Sum possible by merging two given arrays | Python3 implementation of the above approach ; Stores the maximum prefix sum of the array A [ ] ; Traverse the array A [ ] ; Stores the maximum prefix sum of the array B [ ] ; Traverse the array B [ ] ; Driver code',
'code': 'def maxPresum ( a , b ) : NEW_LINE INDENT X = max ( a [ 0 ] , 0 ) NEW_LINE for i in range ( 1 , len ( a ) ) : NEW_LINE INDENT a [ i ] += a [ i - 1 ] NEW_LINE X = max ( X , a [ i ] ) NEW_LINE DEDENT Y = max ( b [ 0 ] , 0 ) NEW_LINE for i in range ( 1 , len ( b ) ) : NEW_LINE INDENT b [ i ] += b [ i - 1 ] NEW_LINE Y = max ( Y , b [ i ] ) NEW_LINE DEDENT return X + Y NEW_LINE DEDENT A = [ 2 , - 1 , 4 , - 5 ] NEW_LINE B = [ 4 , - 3 , 12 , 4 , - 3 ] NEW_LINE print ( maxPresum ( A , B ) ) NEW_LINE'}
Note that the data undergo some tokenization hence the additional whitespaces and the use of NEW_LINE instead of \n
and INDENT instead of \t
, DEDENT to cancel indentation...
Data Fields
- text: natural language description/comment
- code: code at snippet/program level
Data Splits
Each subset has three splits: train, test and validation.
Citation Information
@misc{zhu2022xlcost,
title = {XLCoST: A Benchmark Dataset for Cross-lingual Code Intelligence},
url = {https://arxiv.org/abs/2206.08474},
author = {Zhu, Ming and Jain, Aneesh and Suresh, Karthik and Ravindran, Roshan and Tipirneni, Sindhu and Reddy, Chandan K.},
year = {2022},
eprint={2206.08474},
archivePrefix={arXiv}
}
- Downloads last month
- 586