text
stringlengths 17
4.49k
| code
stringlengths 49
5.46k
|
---|---|
Minimum length subarray containing all unique elements after Q operations | C ++ implementation to find the minimum size subarray containing all unique elements after processing the array for K queries of ranges ; Function to find minimum size subarray of all array elements ; Updating the array after processing each query ; Making it to 0 - indexing ; Prefix sum array concept is used to obtain the count array ; Iterating over the array to get the final array ; Variable to get count of all unique elements ; Hash to maintain perviously occurred elements ; Loop to find the all unique elements ; array to maintain counter of encountered elements ; variable to store answer ; Using two pointers approach ; Increment counter if occurred once ; when all unique elements are found ; update answer with minimum size ; decrement count of elements from left ; decrement counter ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int subarrayLength ( int A [ ] , int R [ ] [ 2 ] , int N , int M ) { for ( int i = 0 ; i < M ; ++ i ) { int l = R [ i ] [ 0 ] , r = R [ i ] [ 1 ] + 1 ; l -- ; r -- ; A [ l ] ++ ; if ( r < N ) A [ r ] -- ; } for ( int i = 1 ; i < N ; ++ i ) { A [ i ] += A [ i - 1 ] ; } int count = 0 ; unordered_set < int > s ; for ( int i = 0 ; i < N ; ++ i ) { if ( s . find ( A [ i ] ) == s . end ( ) ) count ++ ; s . insert ( A [ i ] ) ; } vector < int > repeat ( count + 1 , 0 ) ; int ans = N ; int counter = 0 , left = 0 , right = 0 ; while ( right < N ) { int cur_element = A [ right ] ; repeat [ cur_element ] += 1 ; if ( repeat [ cur_element ] == 1 ) ++ counter ; while ( counter == count ) { ans = min ( ans , right - left + 1 ) ; cur_element = A [ left ] ; repeat [ cur_element ] -= 1 ; ++ left ; if ( repeat [ cur_element ] == 0 ) -- counter ; } ++ right ; } return ans ; } int main ( ) { int N = 8 , queries = 6 ; int Q [ ] [ 2 ] = { { 1 , 4 } , { 3 , 4 } , { 4 , 5 } , { 5 , 5 } , { 7 , 8 } , { 8 , 8 } } ; int A [ N ] = { 0 } ; cout << subarrayLength ( A , Q , N , queries ) ; return 0 ; } |
Elements of Array which can be expressed as power of prime numbers | C ++ program to print all elements of Array which can be expressed as power of prime numbers ; Function to mark all the exponent of prime numbers ; If number is prime then marking all of its exponent true ; Function to display all required elements ; Function to print the required numbers ; To find the largest number ; Function call to mark all the Exponential prime nos . ; Function call ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; void ModifiedSieveOfEratosthenes ( int N , bool Expo_Prime [ ] ) { bool primes [ N ] ; memset ( primes , true , sizeof ( primes ) ) ; for ( int i = 2 ; i < N ; i ++ ) { if ( primes [ i ] ) { int no = i ; while ( no <= N ) { Expo_Prime [ no ] = true ; no *= i ; } for ( int j = i * i ; j < N ; j += i ) primes [ j ] = false ; } } } void Display ( int arr [ ] , bool Expo_Prime [ ] , int n ) { for ( int i = 0 ; i < n ; i ++ ) if ( Expo_Prime [ arr [ i ] ] ) cout << arr [ i ] << " β " ; } void FindExpoPrime ( int arr [ ] , int n ) { int max = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( max < arr [ i ] ) max = arr [ i ] ; } bool Expo_Prime [ max + 1 ] ; memset ( Expo_Prime , false , sizeof ( Expo_Prime ) ) ; ModifiedSieveOfEratosthenes ( max + 1 , Expo_Prime ) ; Display ( arr , Expo_Prime , n ) ; } int main ( ) { int arr [ ] = { 4 , 6 , 9 , 16 , 1 , 3 , 12 , 36 , 625 , 1000 } ; int n = sizeof ( arr ) / sizeof ( int ) ; FindExpoPrime ( arr , n ) ; return 0 ; } |
Elements of Array which can be expressed as power of some integer to given exponent K | C ++ implementation to print elements of the Array which can be expressed as power of some integer to given exponent K ; Method returns Nth power of A ; Smaller eps , denotes more accuracy ; Initializing difference between two roots by INT_MAX ; x ^ K denotes current value of x ; loop untill we reach desired accuracy ; calculating current value from previous value by newton 's method ; Function to check whether its k root is an integer or not ; Function to find the numbers ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; #define ll long long NEW_LINE double nthRoot ( ll A , ll N ) { double xPre = 7 ; double eps = 1e-3 ; double delX = INT_MAX ; double xK ; while ( delX > eps ) { xK = ( ( N - 1.0 ) * xPre + ( double ) A / pow ( xPre , N - 1 ) ) / ( double ) N ; delX = abs ( xK - xPre ) ; xPre = xK ; } return xK ; } bool check ( ll no , int k ) { double kth_root = nthRoot ( no , k ) ; ll num = kth_root ; if ( abs ( num - kth_root ) < 1e-4 ) return true ; return false ; } void printExpo ( ll arr [ ] , int n , int k ) { for ( int i = 0 ; i < n ; i ++ ) { if ( check ( arr [ i ] , k ) ) cout << arr [ i ] << " β " ; } } int main ( ) { int K = 6 ; ll arr [ ] = { 46656 , 64 , 256 , 729 , 16 , 1000 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; printExpo ( arr , n , K ) ; return 0 ; } |
Count of subsequences whose product is a difference of square of two integers | C ++ implementation to count the number of contiguous subsequences whose product can be expressed as the square of difference of two integers ; Function to count the number of contiguous subsequences whose product can be expressed as square of difference of two integers ; Iterating through the array ; Check if that number can be expressed as the square of difference of two numbers ; Variable to compute the product ; Finding the remaining subsequences ; Check if that number can be expressed as the square of difference of two numbers ; Return the number of subsequences ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int CntcontSubs ( int a [ ] , int n ) { int c = 0 , d = 0 , i , sum = 1 , j ; for ( i = 0 ; i < n ; i ++ ) { if ( a [ i ] % 2 != 0 a [ i ] % 4 == 0 ) d ++ ; sum = a [ i ] ; for ( j = i + 1 ; j < n ; j ++ ) { sum = sum * a [ j ] ; if ( sum % 2 != 0 sum % 4 == 0 ) c ++ ; } sum = 1 ; } return c + d ; } int main ( ) { int arr [ ] = { 5 , 4 , 2 , 9 , 8 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << CntcontSubs ( arr , n ) ; return 0 ; } |
Count of subsequences whose product is a difference of square of two integers | C ++ implementation to count all the contiguous subsequences whose product is expressed as the square of the difference of two integers ; Function to count all the contiguous subsequences whose product is expressed as the square of the difference of two integers ; Creating vectors to store the remainders and the subsequences ; Iterating through the array ; Finding the remainder when the element is divided by 4 ; Bringing all the elements in the range [ 0 , 3 ] ; If the remainder is 2 , store the index of the ; If the remainder is 2 , store the index of the ; Finding the total number of subsequences ; If there are no numbers which yield the remainder 2 ; Iterating through the vector ; If the element is 2 , find the nearest 2 or 0 and find the number of elements between them ; Returning the count ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int CntcontSubs ( int a [ ] , int n ) { int prod = 1 ; vector < pair < int , int > > vect ; vect . push_back ( make_pair ( 0 , 2 ) ) ; vector < int > two , zero ; for ( int i = 0 ; i < n ; i ++ ) { a [ i ] = a [ i ] % 4 ; if ( a [ i ] < 0 ) a [ i ] = a [ i ] + 4 ; if ( a [ i ] == 2 ) two . push_back ( i + 1 ) ; if ( a [ i ] == 0 ) zero . push_back ( i + 1 ) ; if ( a [ i ] == 0 a [ i ] == 2 ) vect . push_back ( make_pair ( i + 1 , a [ i ] ) ) ; } vect . push_back ( make_pair ( n + 1 , 2 ) ) ; int total = ( n * ( n + 1 ) ) / 2 ; if ( two . empty ( ) ) return total ; else { int sum = 0 ; int pos1 = -1 , pos2 = -1 , pos3 = -1 ; int sz = vect . size ( ) ; for ( int i = 1 ; i + 1 < sz ; i ++ ) { if ( vect [ i ] . second == 2 ) { sum += ( vect [ i ] . first - vect [ i - 1 ] . first ) * ( vect [ i + 1 ] . first - vect [ i ] . first ) - 1 ; } } return total - sum - two . size ( ) ; } } int main ( ) { int a [ ] = { 5 , 4 , 2 , 9 , 8 } ; int n = sizeof ( a ) / sizeof ( a [ 0 ] ) ; cout << CntcontSubs ( a , n ) ; return 0 ; } |
Count of possible subarrays and subsequences using given length of Array | C ++ implementation to count the subarray and subsequence of given length of the array ; Function to count the subarray for the given array ; Function to count the subsequence for the given array length ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int countSubarray ( int n ) { return ( ( n ) * ( n + 1 ) ) / 2 ; } int countSubsequence ( int n ) { return pow ( 2 , n ) ; } int main ( ) { int n = 5 ; cout << ( countSubarray ( n ) ) << endl ; cout << ( countSubsequence ( n ) ) << endl ; return 0 ; } |
Program for finding the Integral of a given function using Boole 's Rule | C ++ program to implement Boole 's Rule on the given function ; Function to return the value of f ( x ) for the given value of x ; Function to computes the integrand of y at the given intervals of x with step size h and the initial limit a and final limit b ; Number of intervals ; Computing the step size ; Substituing a = 0 , b = 4 and h = 1 ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; float y ( float x ) { return ( 1 / ( 1 + x ) ) ; } float BooleRule ( float a , float b ) { int n = 4 ; int h ; h = ( ( b - a ) / n ) ; float sum = 0 ; float bl = ( ( 7 * y ( a ) + 32 * y ( a + h ) + 12 * y ( a + 2 * h ) + 32 * y ( a + 3 * h ) + 7 * y ( a + 4 * h ) ) * 2 * h / 45 ) ; sum = sum + bl ; return sum ; } int main ( ) { float lowlimit = 0 ; float upplimit = 4 ; cout << fixed << setprecision ( 4 ) << " f ( x ) β = β " << BooleRule ( 0 , 4 ) ; return 0 ; } |
Number of subsets with same AND , OR and XOR values in an Array | C ++ program to find the number of subsets with equal bitwise AND , OR and XOR values ; Function to find the number of subsets with equal bitwise AND , OR and XOR values ; Precompute the modded powers of two for subset counting ; Loop to iterate and find the modded powers of two for subset counting ; Map to store the frequency of each element ; Loop to compute the frequency ; For every element > 0 , the number of subsets formed using this element only is equal to 2 ^ ( frequency [ element ] - 1 ) . And for 0 , we have to find all the subsets , so 2 ^ ( frequency [ element ] ) - 1 ; If element is greater than 0 ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; const int mod = 1000000007 ; int countSubsets ( int a [ ] , int n ) { int answer = 0 ; int powerOfTwo [ 100005 ] ; powerOfTwo [ 0 ] = 1 ; for ( int i = 1 ; i < 100005 ; i ++ ) powerOfTwo [ i ] = ( powerOfTwo [ i - 1 ] * 2 ) % mod ; unordered_map < int , int > frequency ; for ( int i = 0 ; i < n ; i ++ ) frequency [ a [ i ] ] ++ ; for ( auto el : frequency ) { if ( el . first != 0 ) answer = ( answer % mod + powerOfTwo [ el . second - 1 ] ) % mod ; else answer = ( answer % mod + powerOfTwo [ el . second ] - 1 + mod ) % mod ; } return answer ; } int main ( ) { int N = 6 ; int A [ N ] = { 1 , 3 , 2 , 1 , 2 , 1 } ; cout << countSubsets ( A , N ) ; return 0 ; } |
Sum of all Perfect numbers lying in the range [ L , R ] | C ++ implementation to find the sum of all perfect numbers lying in the range [ L , R ] ; Array to store the sum ; Function to check if a number is a perfect number or not ; Iterating till the square root of the number and checking if the sum of divisors is equal to the number or not ; If it is a perfect number , then return the number ; Else , return 0 ; Function to precompute the sum of perfect squares and store then in an array | #include <bits/stdc++.h> NEW_LINE #define ll int NEW_LINE using namespace std ; long long pref [ 100010 ] ; int isPerfect ( int n ) { int sum = 1 ; for ( int i = 2 ; i * i <= n ; i ++ ) { if ( n % i == 0 ) { if ( i * i != n ) sum = sum + i + n / i ; else sum = sum + i ; } } if ( sum == n && n != 1 ) return n ; return 0 ; } void precomputation ( ) { for ( int i = 1 ; i <= 100000 ; ++ i ) { pref [ i ] = pref [ i - 1 ] + isPerfect ( i ) ; } } int main ( ) { int L = 6 , R = 28 ; precomputation ( ) ; cout << pref [ R ] - pref [ L - 1 ] ; return 0 ; } |
Ternary number system or Base 3 numbers | C ++ program to convert a ternary number to decimal number ; Function to convert a ternary number to a decimal number ; If the number is greater than 0 , compute the decimal representation of the number ; Loop to iterate through the number ; Computing the decimal digit ; Driver code | #include <cstdio> NEW_LINE #include <iostream> NEW_LINE #include <math.h> NEW_LINE using namespace std ; void convertToDecimal ( int N ) { cout << " Decimal β number β of β " << N << " β is : β " ; if ( N != 0 ) { int decimalNumber = 0 , i = 0 , remainder ; while ( N != 0 ) { remainder = N % 10 ; N /= 10 ; decimalNumber += remainder * pow ( 3 , i ) ; ++ i ; } cout << decimalNumber << endl ; } else cout << "0" << endl ; } int main ( ) { int Ternary = 10202202 ; convertToDecimal ( Ternary ) ; return 0 ; } |
Check if a given pair of Numbers are Betrothed numbers or not | C ++ program for the above approach ; Function to check whether N is Perfect Square or not ; Find sqrt ; Function to check whether the given pairs of numbers is Betrothed Numbers or not ; For finding the sum of all the divisors of first number n ; For finding the sum of all the divisors of second number m ; Driver Code ; Function Call | #include <bits/stdc++.h> NEW_LINE using namespace std ; bool isPerfectSquare ( int N ) { double sr = sqrt ( N ) ; return ( sr - floor ( sr ) ) == 0 ; } void BetrothedNumbers ( int n , int m ) { int Sum1 = 1 ; int Sum2 = 1 ; for ( int i = 2 ; i <= sqrt ( n ) ; i ++ ) { if ( n % i == 0 ) { Sum1 += i + ( isPerfectSquare ( n ) ? 0 : n / i ) ; } } for ( int i = 2 ; i <= sqrt ( m ) ; i ++ ) { if ( m % i == 0 ) { Sum2 += i + ( isPerfectSquare ( m ) ? 0 : m / i ) ; } } if ( ( n + 1 == Sum2 ) && ( m + 1 == Sum1 ) ) { cout << " YES " << endl ; } else { cout << " NO " << endl ; } } int main ( ) { int N = 9504 ; int M = 20734 ; BetrothedNumbers ( N , M ) ; return 0 ; } |
Count of numbers upto M with GCD equals to K when paired with M | C ++ program to Count of numbers between 0 to M which have GCD with M equals to K . ; Function to calculate GCD using euler totient function ; Finding the prime factors of limit to calculate it 's euler totient function ; Calculating the euler totient function of ( m / k ) ; Function print the count of numbers whose GCD with M equals to K ; GCD of m with any integer cannot be equal to k ; 0 and m itself will be the only valid integers ; Finding the number upto which coefficient of k can come ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int EulerTotientFunction ( int limit ) { int copy = limit ; vector < int > primes ; for ( int i = 2 ; i * i <= limit ; i ++ ) { if ( limit % i == 0 ) { while ( limit % i == 0 ) { limit /= i ; } primes . push_back ( i ) ; } } if ( limit >= 2 ) { primes . push_back ( limit ) ; } int ans = copy ; for ( auto it : primes ) { ans = ( ans / it ) * ( it - 1 ) ; } return ans ; } void CountGCD ( int m , int k ) { if ( m % k != 0 ) { cout << 0 << endl ; return ; } if ( m == k ) { cout << 2 << endl ; return ; } int limit = m / k ; int ans = EulerTotientFunction ( limit ) ; cout << ans << endl ; } int main ( ) { int M = 9 ; int K = 1 ; CountGCD ( M , K ) ; return 0 ; } |
Find the product of sum of two diagonals of a square Matrix | C ++ program to find the product of the sum of diagonals . ; Function to find the product of the sum of diagonals . ; Initialize sums of diagonals ; Return the answer ; Driven code ; Function call | #include <bits/stdc++.h> NEW_LINE using namespace std ; long long product ( vector < vector < int > > & mat , int n ) { long long d1 = 0 , d2 = 0 ; for ( int i = 0 ; i < n ; i ++ ) { d1 += mat [ i ] [ i ] ; d2 += mat [ i ] [ n - i - 1 ] ; } return 1LL * d1 * d2 ; } int main ( ) { vector < vector < int > > mat = { { 5 , 8 , 1 } , { 5 , 10 , 3 } , { -6 , 17 , -9 } } ; int n = mat . size ( ) ; cout << product ( mat , n ) ; return 0 ; } |
Program to calculate Percentile of a student based on rank | C ++ program to calculate Percentile of a student based on rank ; Program to calculate the percentile ; flat variable to store the result ; calculate and return the percentile ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; float getPercentile ( int rank , int students ) { float result = float ( students - rank ) / students * 100 ; return result ; } int main ( ) { int your_rank = 805 ; int total_students = 97481 ; cout << getPercentile ( your_rank , total_students ) ; } |
Sum of numbers in the Kth level of a Fibonacci triangle | C ++ implementation to find the Sum of numbers in the Kth level of a Fibonacci triangle ; Function to return the nth Fibonacci number ; Function to return the required sum of the array ; Using our deduced result ; Function to return the sum of fibonacci in the Kth array ; Count of fibonacci which are in the arrays from 1 to k - 1 ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; #define MAX 1000000 NEW_LINE int fib ( int n ) { double phi = ( 1 + sqrt ( 5 ) ) / 2 ; return round ( pow ( phi , n ) / sqrt ( 5 ) ) ; } int calculateSum ( int l , int r ) { int sum = fib ( r + 2 ) - fib ( l + 1 ) ; return sum ; } int sumFibonacci ( int k ) { int l = ( k * ( k - 1 ) ) / 2 ; int r = l + k ; int sum = calculateSum ( l , r - 1 ) ; return sum ; } int main ( ) { int k = 3 ; cout << sumFibonacci ( k ) ; return 0 ; } |
Print the sequence of size N in which every term is sum of previous K terms | C ++ implementation to find the series in which every term is sum of previous K terms ; Function to generate the series in the form of array ; Pick a starting point ; Find the sum of all elements till count < K ; Find the value of sum at i position ; Driver Code | #include <iostream> NEW_LINE using namespace std ; void sumOfPrevK ( int N , int K ) { int arr [ N ] ; arr [ 0 ] = 1 ; for ( int i = 1 ; i < N ; i ++ ) { int j = i - 1 , count = 0 , sum = 0 ; while ( j >= 0 && count < K ) { sum += arr [ j ] ; j -- ; count ++ ; } arr [ i ] = sum ; } for ( int i = 0 ; i < N ; i ++ ) { cout << arr [ i ] << " β " ; } } int main ( ) { int N = 10 , K = 4 ; sumOfPrevK ( N , K ) ; return 0 ; } |
Print the sequence of size N in which every term is sum of previous K terms | C ++ implementation to find the series in which every term is sum of previous K terms ; Function to generate the series in the form of array ; Pick a starting point ; Computing the previous sum ; Loop to print the series ; Driver Code | #include <iostream> NEW_LINE using namespace std ; void sumOfPrevK ( int N , int K ) { int arr [ N ] , prevsum = 0 ; arr [ 0 ] = 1 ; for ( int i = 0 ; i < N - 1 ; i ++ ) { if ( i < K ) { arr [ i + 1 ] = arr [ i ] + prevsum ; prevsum = arr [ i + 1 ] ; } else { arr [ i + 1 ] = arr [ i ] + prevsum - arr [ i + 1 - K ] ; prevsum = arr [ i + 1 ] ; } } for ( int i = 0 ; i < N ; i ++ ) { cout << arr [ i ] << " β " ; } } int main ( ) { int N = 8 , K = 3 ; sumOfPrevK ( N , K ) ; return 0 ; } |
Maximum GCD of all subarrays of length at least 2 | C ++ program for the above approach ; Function to find GCD ; To store the maximum GCD ; Traverse the array ; Find GCD of the consecutive element ; If calculated GCD > maxGCD then update it ; Print the maximum GCD ; Driver Code ; 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 ) ; } void findMaxGCD ( int arr [ ] , int n ) { int maxGCD = 0 ; for ( int i = 0 ; i < n - 1 ; i ++ ) { int val = gcd ( arr [ i ] , arr [ i + 1 ] ) ; if ( val > maxGCD ) { maxGCD = val ; } } cout << maxGCD << endl ; } int main ( ) { int arr [ ] = { 3 , 18 , 9 , 9 , 5 , 15 , 8 , 7 , 6 , 9 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; findMaxGCD ( arr , n ) ; return 0 ; } |
Sum of elements of an AP in the given range | C ++ program to find the sum of elements of an AP in the given range ; Function to find sum in the given range ; Find the value of k ; Find the common difference ; Find the sum ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int findSum ( int * arr , int n , int left , int right ) { int k = right - left ; int d = arr [ 1 ] - arr [ 0 ] ; int ans = arr [ left - 1 ] * ( k + 1 ) ; ans = ans + ( d * ( k * ( k + 1 ) ) ) / 2 ; return ans ; } int main ( ) { int arr [ ] = { 2 , 4 , 6 , 8 , 10 , 12 , 14 , 16 } ; int queries = 3 ; int q [ queries ] [ 2 ] = { { 2 , 4 } , { 2 , 6 } , { 5 , 6 } } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; for ( int i = 0 ; i < queries ; i ++ ) cout << findSum ( arr , n , q [ i ] [ 0 ] , q [ i ] [ 1 ] ) << endl ; } |
Check if a subarray exists with sum greater than the given Array | C ++ program to check if a subarray exists with sum greater than the given Array ; Function to check whether there exists a subarray whose sum is greater than or equal to sum of given array elements ; Initialize sum with 0 ; Checking possible prefix subarrays . If sum of them is less than or equal to zero , then return 1 ; again reset sum to zero ; Checking possible suffix subarrays . If sum of them is less than or equal to zero , then return 1 ; Otherwise return 0 ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int subarrayPossible ( int arr [ ] , int n ) { int sum = 0 ; for ( int i = 0 ; i < n ; i ++ ) { sum += arr [ i ] ; if ( sum <= 0 ) return 1 ; } sum = 0 ; for ( int i = n - 1 ; i >= 0 ; i -- ) { sum += arr [ i ] ; if ( sum <= 0 ) return 1 ; } return 0 ; } int main ( ) { int arr [ ] = { 10 , 5 , -12 , 7 , -10 , 20 , 30 , -10 , 50 , 60 } ; int size = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; if ( subarrayPossible ( arr , size ) ) cout << " Yes " << " STRNEWLINE " ; else cout << " No " << " STRNEWLINE " ; return 0 ; } |
Finding Integreand using Weedle 's Rule | C ++ program to Implement Weedle 's Rule ; A sample function f ( x ) = 1 / ( 1 + x ^ 2 ) ; Function to find the integral value of f ( x ) with step size h , with initial lower limit and upper limit a and b ; Find step size h ; To store the final sum ; Find sum using Weedle 's Formula ; Return the final sum ; Driver Code ; lower limit and upper limit ; Function Call | #include <bits/stdc++.h> NEW_LINE using namespace std ; float y ( float x ) { float num = 1 ; float denom = 1.0 + x * x ; return num / denom ; } float WeedleRule ( float a , float b ) { double h = ( b - a ) / 6 ; float sum = 0 ; sum = sum + ( ( ( 3 * h ) / 10 ) * ( y ( a ) + y ( a + 2 * h ) + 5 * y ( a + h ) + 6 * y ( a + 3 * h ) + y ( a + 4 * h ) + 5 * y ( a + 5 * h ) + y ( a + 6 * h ) ) ) ; return sum ; } int main ( ) { float a = 0 , b = 6 ; cout << " f ( x ) β = β " << fixed << WeedleRule ( a , b ) ; return 0 ; } |
Find the minimum number to be added to N to make it a prime number | C ++ program to find the minimum number to be added to N to make it a prime number ; Function to check if a given number is a prime or not ; Base cases ; This is checked so that we can skip middle five numbers in below loop ; For all the remaining numbers , check if any number is a factor if the number or not ; If none of the above numbers are the factors for the number , then the given number is prime ; Function to return the smallest number to be added to make a number prime ; Base case ; Loop continuously until isPrime returns true for a number greater than n ; If the number is not a prime , then increment the number by 1 and the counter which stores the number to be added ; 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 ; } int findSmallest ( int N ) { if ( N == 0 ) return 2 ; if ( N == 1 ) return 1 ; int prime = N , counter = 0 ; bool found = false ; while ( ! found ) { if ( isPrime ( prime ) ) found = true ; else { prime ++ ; counter ++ ; } } return counter ; } int main ( ) { int N = 10 ; cout << findSmallest ( N ) ; return 0 ; } |
Find the position of the given Prime Number | C ++ program to find the position of the given prime number ; 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 ; Driver code | #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 main ( ) { sieve ( ) ; int n = 11 ; cout << position [ n ] ; return 0 ; } |
Minimum possible sum of array elements after performing the given operation | C ++ program to find the minimum possible sum of the array elements after performing the given operation ; Function to find the maximum sum of the sub array ; max_so_far represents the maximum sum found till now and max_ending_here represents the maximum sum ending at a specific index ; Iterating through the array to find the maximum sum of the subarray ; If the maximum sum ending at a specific index becomes less than 0 , then making it equal to 0. ; Function to find the minimum possible sum of the array elements after performing the given operation ; Finding the sum of the array ; Computing the minimum sum of the array ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; double maxSubArraySum ( double a [ ] , int size ) { double max_so_far = INT_MIN , max_ending_here = 0 ; for ( int i = 0 ; i < size ; i ++ ) { max_ending_here = max_ending_here + a [ i ] ; if ( max_so_far < max_ending_here ) max_so_far = max_ending_here ; if ( max_ending_here < 0 ) max_ending_here = 0 ; } return max_so_far ; } double minPossibleSum ( double a [ ] , int n , double x ) { double mxSum = maxSubArraySum ( a , n ) ; double sum = 0 ; for ( int i = 0 ; i < n ; i ++ ) { sum += a [ i ] ; } sum = sum - mxSum + mxSum / x ; cout << setprecision ( 2 ) << sum << endl ; } int main ( ) { int N = 3 ; double X = 2 ; double A [ N ] = { 1 , -2 , 3 } ; minPossibleSum ( A , N , X ) ; } |
Print the two possible permutations from a given sequence | C ++ program to print two permutations from a given sequence ; Function to check if the sequence is concatenation of two permutations or not ; Computing the sum of all the elements in the array ; Computing the prefix sum for all the elements in the array ; Iterating through the i from lengths 1 to n - 1 ; Sum of first i + 1 elements ; Sum of remaining n - i - 1 elements ; Lengths of the 2 permutations ; Checking if the sums satisfy the formula or not ; Function to print the two permutations ; Print the first permutation ; Print the second permutation ; Function to find the two permutations from the given sequence ; If the sequence is not a concatenation of two permutations ; Find the largest element in the array and set the lengths of the permutations accordingly ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; bool checkPermutation ( int arr [ ] , int n ) { long long sum = 0 ; for ( int i = 0 ; i < n ; i ++ ) sum += arr [ i ] ; long long prefix [ n + 1 ] = { 0 } ; prefix [ 0 ] = arr [ 0 ] ; for ( int i = 1 ; i < n ; i ++ ) prefix [ i ] = prefix [ i - 1 ] + arr [ i ] ; for ( int i = 0 ; i < n - 1 ; i ++ ) { long long lsum = prefix [ i ] ; long long rsum = sum - prefix [ i ] ; long long l_len = i + 1 , r_len = n - i - 1 ; if ( ( ( 2 * lsum ) == ( l_len * ( l_len + 1 ) ) ) && ( ( 2 * rsum ) == ( r_len * ( r_len + 1 ) ) ) ) return true ; } return false ; } void printPermutations ( int arr [ ] , int n , int l1 , int l2 ) { for ( int i = 0 ; i < l1 ; i ++ ) { cout << arr [ i ] << " β " ; } cout << endl ; for ( int i = l1 ; i < n ; i ++ ) { cout << arr [ i ] << " β " ; } } void findPermutations ( int arr [ ] , int n ) { if ( ! checkPermutation ( arr , n ) ) { cout << " Not β Possible " ; return ; } int l1 = 0 , l2 = 0 ; l1 = * max_element ( arr , arr + n ) ; l2 = n - l1 ; set < int > s1 , s2 ; for ( int i = 0 ; i < l1 ; i ++ ) s1 . insert ( arr [ i ] ) ; for ( int i = l1 ; i < n ; i ++ ) s2 . insert ( arr [ i ] ) ; if ( s1 . size ( ) == l1 && s2 . size ( ) == l2 ) printPermutations ( arr , n , l1 , l2 ) ; else { swap ( l1 , l2 ) ; printPermutations ( arr , n , l1 , l2 ) ; } } int main ( ) { int arr [ ] = { 2 , 1 , 3 , 4 , 5 , 6 , 7 , 8 , 9 , 1 , 10 , 2 } ; int n = sizeof ( arr ) / sizeof ( int ) ; findPermutations ( arr , n ) ; return 0 ; } |
Count pairs in array such that one element is reverse of another | C ++ program to count the pairs in array such that one element is reverse of another ; Function to reverse the digits of the number ; Loop to iterate till the number is greater than 0 ; Extract the last digit and keep multiplying it by 10 to get the reverse of the number ; Function to find the pairs from the array such that one number is reverse of the other ; Iterate through all pairs ; Increment count if one is the reverse of other ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int reverse ( int num ) { int rev_num = 0 ; while ( num > 0 ) { rev_num = rev_num * 10 + num % 10 ; num = num / 10 ; } return rev_num ; } int countReverse ( int arr [ ] , int n ) { int res = 0 ; for ( int i = 0 ; i < n ; i ++ ) for ( int j = i + 1 ; j < n ; j ++ ) if ( reverse ( arr [ i ] ) == arr [ j ] ) { res ++ ; } return res ; } int main ( ) { int a [ ] = { 16 , 61 , 12 , 21 , 25 } ; int n = sizeof ( a ) / sizeof ( a [ 0 ] ) ; cout << countReverse ( a , n ) ; return 0 ; } |
Count pairs in array such that one element is reverse of another | C ++ program to count the pairs in array such that one element is reverse of another ; Function to reverse the digits of the number ; Loop to iterate till the number is greater than 0 ; Extract the last digit and keep multiplying it by 10 to get the reverse of the number ; Function to find the pairs from the array such that one number is reverse of the other ; Iterate over every element in the array and increase the frequency of the element in hash map ; Iterate over every element in the array ; remove the current element from the hash map by decreasing the frequency to avoid counting when the number is a palindrome or when we visit its reverse ; Increment the count by the frequency of reverse of the number ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int reverse ( int num ) { int rev_num = 0 ; while ( num > 0 ) { rev_num = rev_num * 10 + num % 10 ; num = num / 10 ; } return rev_num ; } int countReverse ( int arr [ ] , int n ) { unordered_map < int , int > freq ; for ( int i = 0 ; i < n ; ++ i ) ++ freq [ arr [ i ] ] ; int res = 0 ; for ( int i = 0 ; i < n ; i ++ ) { -- freq [ arr [ i ] ] ; res += freq [ reverse ( arr [ i ] ) ] ; } return res ; } int main ( ) { int a [ ] = { 16 , 61 , 12 , 21 , 25 } ; int n = sizeof ( a ) / sizeof ( a [ 0 ] ) ; cout << countReverse ( a , n ) << ' ' ; return 0 ; } |
Sum of i * countDigits ( i ) ^ countDigits ( i ) for all i in range [ L , R ] | C ++ program to find the required sum ; Function to return the required sum ; Iterating for all the number of digits from 1 to 10 ; If the range is valid ; Sum of AP ; Computing the next minimum and maximum numbers by for the ( i + 1 ) - th digit ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; #define MOD 1000000007 NEW_LINE int rangeSum ( int l , int r ) { int a = 1 , b = 9 , res = 0 ; for ( int i = 1 ; i <= 10 ; i ++ ) { int L = max ( l , a ) ; int R = min ( r , b ) ; if ( L <= R ) { int sum = ( L + R ) * ( R - L + 1 ) / 2 ; res += pow ( i , i ) * ( sum % MOD ) ; res %= MOD ; } a = a * 10 ; b = b * 10 + 9 ; } return res ; } int main ( ) { int l = 98 , r = 102 ; cout << rangeSum ( l , r ) ; return 0 ; } |
Trial division Algorithm for Prime Factorization | CPP implementation of Trial Division Algorithm ; Function to check if a number is a prime number or not ; Initializing with the value 2 from where the number is checked ; Computing the square root of the number N ; While loop till the square root of N ; If any of the numbers between [ 2 , sqrt ( N ) ] is a factor of N Then the number is composite ; If none of the numbers is a factor , then it is a prime number ; Driver code ; To check if a number is a prime or not | #include <bits/stdc++.h> NEW_LINE using namespace std ; int TrialDivision ( int N ) { int i = 2 ; int k = ceil ( sqrt ( N ) ) ; while ( i <= k ) { if ( N % i == 0 ) return 0 ; i += 1 ; } return 1 ; } int main ( ) { int N = 49 ; int p = TrialDivision ( N ) ; if ( p ) cout << ( " Prime " ) ; else cout << ( " Composite " ) ; return 0 ; } |
Find if it is possible to choose subarray that it contains exactly K even integers | C ++ program to check if it is possible to choose a subarray that contains exactly K even integers ; Function to check if it is possible to choose a subarray that contains exactly K even integers ; Variable to store the count of even numbers ; If we have to select 0 even numbers but there is all odd numbers in the array ; If the count of even numbers is greater than or equal to K then we can select a subarray with exactly K even integers ; If the count of even numbers is less than K then we cannot select any subarray with exactly K even integers ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; void isPossible ( int A [ ] , int n , int k ) { int countOfTwo = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( A [ i ] % 2 == 0 ) { countOfTwo ++ ; } } if ( k == 0 && countOfTwo == n ) cout << " NO STRNEWLINE " ; else if ( countOfTwo >= k ) { cout << " Yes STRNEWLINE " ; } else cout << " No STRNEWLINE " ; } int main ( ) { int arr [ ] = { 1 , 2 , 4 , 5 } ; int K = 2 ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; isPossible ( arr , N , K ) ; return 0 ; } |
Count of pairs ( A , B ) in range 1 to N such that last digit of A is equal to the first digit of B | C ++ program to implement the above approach ; Function to Count of pairs ( A , B ) in range 1 to N ; count C i , j ; Calculate number of pairs ; Driver code ; Function call | #include <bits/stdc++.h> NEW_LINE using namespace std ; int pairs ( int n ) { vector < vector < int > > c ( 10 , vector < int > ( 10 , 0 ) ) ; int tmp = 1 ; for ( int i = 1 ; i <= n ; i ++ ) { if ( i >= tmp * 10 ) tmp *= 10 ; c [ i / tmp ] [ i % 10 ] ++ ; } long long ans = 0 ; for ( int i = 1 ; i < 10 ; i ++ ) for ( int j = 1 ; j < 10 ; j ++ ) ans += ( long long ) c [ i ] [ j ] * c [ j ] [ i ] ; return ans ; } int main ( ) { int n = 25 ; cout << pairs ( n ) ; return 0 ; } |
Count ways to divide C in two parts and add to A and B to make A strictly greater than B | C ++ implementation of the above approach ; Function to count the number of ways to divide C into two parts and add to A and B such that A is strictly greater than B ; Minimum value added to A to satisfy the given relation ; Number of different values of A , i . e . , number of ways to divide C ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int countWays ( int A , int B , int C ) { int minAddA = max ( 0 , ( C + B - A + 2 ) / 2 ) ; int count_ways = max ( C - minAddA + 1 , 0 ) ; return count_ways ; } int main ( ) { int A = 3 , B = 5 , C = 5 ; cout << countWays ( A , B , C ) ; return 0 ; } |
GCD of elements occurring Fibonacci number of times in an Array | C ++ program to find the GCD of elements which occur Fibonacci number of times ; Function to create hash table to check Fibonacci numbers ; Inserting the first two numbers into the hash ; Adding the remaining Fibonacci numbers using the previously added elements ; Function to return the GCD of elements in an array having fibonacci frequency ; Creating the hash ; Map is used to store the frequencies of the elements ; Iterating through the array ; Traverse the map using iterators ; Calculate the gcd of elements having fibonacci frequencies ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; void createHash ( set < int > & hash , int maxElement ) { int prev = 0 , curr = 1 ; hash . insert ( prev ) ; hash . insert ( curr ) ; while ( curr <= maxElement ) { int temp = curr + prev ; hash . insert ( temp ) ; prev = curr ; curr = temp ; } } int gcdFibonacciFreq ( int arr [ ] , int n ) { set < int > hash ; createHash ( hash , * max_element ( arr , arr + n ) ) ; int i , j ; unordered_map < int , int > m ; for ( i = 0 ; i < n ; i ++ ) m [ arr [ i ] ] ++ ; int gcd = 0 ; for ( auto it = m . begin ( ) ; it != m . end ( ) ; it ++ ) { if ( hash . find ( it -> second ) != hash . end ( ) ) { gcd = __gcd ( gcd , it -> first ) ; } } return gcd ; } int main ( ) { int arr [ ] = { 5 , 3 , 6 , 5 , 6 , 6 , 5 , 5 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << gcdFibonacciFreq ( arr , n ) ; return 0 ; } |
Program to print the series 1 , 9 , 17 , 33 , 49 , 73 , 97. . . till N terms | C ++ implementation of the above approach ; Function to print the series ; Generate the ith term and print it ; Driver Code | #include " bits / stdc + + . h " NEW_LINE using namespace std ; void printSeries ( int N ) { int ith_term = 0 ; for ( int i = 1 ; i <= N ; i ++ ) { ith_term = i % 2 == 0 ? 2 * i * i + 1 : 2 * i * i - 1 ; cout << ith_term << " , β " ; } } int main ( ) { int N = 7 ; printSeries ( N ) ; return 0 ; } |
Find Nth term of the series where each term differs by 6 and 2 alternately | C ++ program for the above approach ; Function to find Nth term ; Iterate from 1 till Nth term ; Check if i is even and then add 6 ; Else add 2 ; Print ans ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; void findNthTerm ( int N ) { int ans = 0 ; for ( int i = 0 ; i < N ; i ++ ) { if ( i % 2 == 0 ) { ans = ans + 6 ; } else { ans = ans + 2 ; } } cout << ans << endl ; } int main ( ) { int N = 3 ; findNthTerm ( N ) ; return 0 ; } |
Find the number of ordered pairs such that a * p + b * q = N , where p and q are primes | C ++ program to find the number of ordered pairs such that a * p + b * q = N where p and q are primes ; Sieve of erastothenes to store the prime numbers and their frequency in form a * p + b * q ; Performing Sieve of Eratosthenes to find the prime numbers unto 10001 ; Loop to find the number of ordered pairs for every combination of the prime numbers ; Driver code ; Printing the number of ordered pairs for every query | #include <bits/stdc++.h> NEW_LINE #define size 10001 NEW_LINE using namespace std ; int prime [ size ] ; int freq [ size ] ; void sieve ( int a , int b ) { prime [ 1 ] = 1 ; for ( int i = 2 ; i * i < size ; i ++ ) { if ( prime [ i ] == 0 ) { for ( int j = i * 2 ; j < size ; j += i ) prime [ j ] = 1 ; } } for ( int p = 1 ; p < size ; p ++ ) { for ( int q = 1 ; q < size ; q ++ ) { if ( prime [ p ] == 0 && prime [ q ] == 0 && a * p + b * q < size ) { freq [ a * p + b * q ] ++ ; } } } } int main ( ) { int queries = 2 , a = 1 , b = 2 ; sieve ( a , b ) ; int arr [ queries ] = { 15 , 25 } ; for ( int i = 0 ; i < queries ; i ++ ) { cout << freq [ arr [ i ] ] << " β " ; } return 0 ; } |
Find the Sum of the series 1 / 2 | C ++ program for the above approach ; Function to find the sum of series ; Generate the ith term and add it to the sum if i is even and subtract if i is odd ; Print the sum ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; void printSeriesSum ( int N ) { double sum = 0 ; for ( int i = 1 ; i <= N ; i ++ ) { if ( i & 1 ) { sum += ( double ) i / ( i + 1 ) ; } else { sum -= ( double ) i / ( i + 1 ) ; } } cout << sum << endl ; } int main ( ) { int N = 10 ; printSeriesSum ( N ) ; return 0 ; } |
Find the Sum of the series 1 + 2 + 9 + 64 + 625 + 7776 . . . till N terms | C ++ program for the above approach ; Function to find the sum of series ; Generate the ith term and add it to the sum ; Print the sum ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; void printSeriesSum ( int N ) { long long sum = 0 ; for ( int i = 1 ; i <= N ; i ++ ) { sum += pow ( i , i - 1 ) ; } cout << sum << endl ; } int main ( ) { int N = 5 ; printSeriesSum ( N ) ; return 0 ; } |
Find the Sum of the series 1 + 1 / 3 + 1 / 5 + 1 / 7 + ... till N terms | C ++ program to find the sum of the series 1 + 1 / 3 + 1 / 5 + ... ; Function to find the sum of the given series ; Initialise the sum to 0 ; Generate the ith term and add it to the sum ; Print the final sum ; Driver Code | #include <iostream> NEW_LINE using namespace std ; void printSumSeries ( int N ) { float sum = 0 ; for ( int i = 1 ; i <= N ; i ++ ) { sum += 1.0 / ( 2 * i - 1 ) ; } cout << sum << endl ; } int main ( ) { int N = 6 ; printSumSeries ( N ) ; return 0 ; } |
Find the Sum of the series 1 , 2 , 3 , 6 , 9 , 18 , 27 , 54 , ... till N terms | C ++ program for the above series ; Function to find the sum of series ; Flag to find the multiplicating factor . . i . e , by 2 or 3 / 2 ; First term ; If flag is true , multiply by 2 ; If flag is false , multiply by 3 / 2 ; Update the previous element to nextElement ; Print the sum ; Driver Code | #include <iostream> NEW_LINE using namespace std ; void printSeriesSum ( int N ) { double sum = 0 ; int a = 1 ; int cnt = 0 ; bool flag = true ; sum += a ; while ( cnt < N ) { int nextElement ; if ( flag ) { nextElement = a * 2 ; sum += nextElement ; flag = ! flag ; } else { nextElement = a * 3 / 2 ; sum += nextElement ; flag = ! flag ; } a = nextElement ; cnt ++ ; } cout << sum << endl ; } int main ( ) { int N = 8 ; printSeriesSum ( N ) ; return 0 ; } |
Program to add two integers of given base | C ++ implementation to find the sum of two integers of base B ; Function to find the sum of two integers of base B ; Padding 0 in front of the number to make both numbers equal ; Condition to check if the strings have lengths mis - match ; Loop to find the find the sum of two integers of base B ; Current Place value for the resultant sum ; Update carry ; Find current digit ; Update sum result ; Driver Code ; Function Call | #include <bits/stdc++.h> NEW_LINE using namespace std ; string sumBaseB ( string a , string b , int base ) { int len_a , len_b ; len_a = a . size ( ) ; len_b = b . size ( ) ; string sum , s ; s = " " ; sum = " " ; int diff ; diff = abs ( len_a - len_b ) ; for ( int i = 1 ; i <= diff ; i ++ ) s += "0" ; if ( len_a < len_b ) a = s + a ; else b = s + b ; int curr , carry = 0 ; for ( int i = max ( len_a , len_b ) - 1 ; i > -1 ; i -- ) { curr = carry + ( a [ i ] - '0' ) + ( b [ i ] - '0' ) ; carry = curr / base ; curr = curr % base ; sum = ( char ) ( curr + '0' ) + sum ; } if ( carry > 0 ) sum = ( char ) ( carry + '0' ) + sum ; return sum ; } int main ( ) { string a , b , sum ; int base ; a = "123" ; b = "234" ; base = 6 ; sum = sumBaseB ( a , b , base ) ; cout << sum << endl ; return 0 ; } |
Minimum number of swaps required to make a number divisible by 60 | C ++ program to find minimum number of swap operations required ; Function that print minimum number of swap operations required ; Condition if more than one zero exist ; Condition if zero_exist ; Computing total sum of all digits ; Condition if zero does not exist or the sum is not divisible by 3 ; Condition to find a digit that is multiple of 2 other than one zero ; Condition if multiple of 2 do not exist ; Condition for zero swaps means the number is already is divisible by 60 ; Condition for only one swap ; Otherwise 2 swaps required ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; void MinimumSwapOperations ( string s ) { bool zero_exist = false ; bool multiple_of_2 = false ; int sum = 0 ; int index_of_zero ; bool more_zero = false ; for ( int i = 0 ; i < s . length ( ) ; i ++ ) { int val = s [ i ] - '0' ; if ( zero_exist == true ) more_zero = true ; if ( val == 0 ) { zero_exist = true ; index_of_zero = i ; } sum += val ; } if ( zero_exist == false sum % 3 != 0 ) { cout << " - 1" << " STRNEWLINE " ; return ; } for ( int i = 0 ; i < s . length ( ) ; i ++ ) { int val = s [ i ] - '0' ; if ( val % 2 == 0 && i != index_of_zero ) multiple_of_2 = true ; } if ( multiple_of_2 == false ) { cout << " - 1" << " STRNEWLINE " ; return ; } int last_val = s [ s . length ( ) - 1 ] - '0' ; int second_last_val = s [ s . length ( ) - 2 ] - '0' ; if ( last_val == 0 && second_last_val % 2 == 0 ) cout << 0 << " STRNEWLINE " ; else if ( ( last_val == 0 && second_last_val % 2 != 0 ) || ( last_val % 2 == 0 && second_last_val == 0 ) ) cout << 1 << " STRNEWLINE " ; else if ( more_zero == true && ( last_val == 0 && second_last_val % 2 != 0 ) ) cout << 1 << " STRNEWLINE " ; else cout << 2 << " STRNEWLINE " ; } int main ( ) { string N = "20" ; MinimumSwapOperations ( N ) ; return 0 ; } |
Minimize the cost of selecting two numbers whose product is X | C ++ implementation of the above approach ; max_prime [ i ] represents maximum prime number that divides the number i ; min_prime [ i ] represents minimum prime number that divides the number i ; Function to store the minimum prime factor and the maximum prime factor in two arrays ; Check for prime number if min_prime [ i ] > 0 , then it is not a prime number ; If i is a prime number , then both minimum and maximum prime numbers that divide the number is the number itself ; If this number is being visited for first time then this divisor must be the smallest prime number that divides this number ; The last prime number that divides this number will be maximum . ; Function to minimize the cost of finding two numbers for every number such that the product of those two is equal to X ; Pre - calculation ; If X == 1 , then there is no way to find N and M . Print - 1 ; Case 3 is always valid and cost for that is C + X C for choosing 1 and M = X / 1 ; Case 1 N is prime , first number cost is fixed N is max_prime number divides this number ; If X is prime then the maximum prime number is the number itself . For this case , M becomes 1 and this shouldn 't be considered. ; Find M for this case ; Add cost for the second number also ; Update min_cost , if the cost for prime is minimum ; Case 2 If N is composite For this find the minimum prime number that divides A [ i ] and consider this as M ; Find N for that number ; Check if this number is composite or not if N is prime then there is no way to find any composite number that divides X If N = min_prime [ N ] then N is prime ; Update min_cost , if the cost for the composite is minimum ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; const int MAX = 100000 ; int max_prime [ MAX ] ; int min_prime [ MAX ] ; void sieve ( int n ) { for ( int i = 2 ; i <= n ; ++ i ) { if ( min_prime [ i ] > 0 ) { continue ; } min_prime [ i ] = i ; max_prime [ i ] = i ; int j = i + i ; while ( j <= n ) { if ( min_prime [ j ] == 0 ) { min_prime [ j ] = i ; } max_prime [ j ] = i ; j += i ; } } } int findCost ( int A , int B , int C , int X ) { sieve ( MAX ) ; int N , M ; if ( X == 1 ) { return -1 ; } int min_cost = C + X ; int cost_for_prime = A ; N = max_prime [ X ] ; if ( N != X ) { M = X / N ; cost_for_prime += M ; min_cost = min ( min_cost , cost_for_prime ) ; } M = min_prime [ X ] ; N = X / M ; if ( N != min_prime [ N ] ) { int cost_for_comp = B + M ; min_cost = min ( min_cost , cost_for_comp ) ; } return min_cost ; } int main ( ) { int A = 7 , B = 11 , C = 2 , X = 20 ; cout << findCost ( A , B , C , X ) << " β " ; return 0 ; } |
Count the occurrence of digit K in a given number N using Recursion | C ++ implementation to count the occurrence of a digit in number using Recursion ; Function to count the digit K in the given number N ; Extracting least significant digit ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int countdigits ( int n , int k ) { if ( n == 0 ) return 0 ; int digit = n % 10 ; if ( digit == k ) return 1 + countdigits ( n / 10 , k ) ; return countdigits ( n / 10 , k ) ; } int main ( ) { int n = 1000 ; int k = 0 ; cout << countdigits ( n , k ) << endl ; return 0 ; } |
Product of all Subarrays of an Array | C ++ program to find product of all subarray of an array ; Function to find product of all subarrays ; Variable to store the product ; Compute the product while traversing for subarrays ; Printing product of all subarray ; Driver code ; Function call | #include <bits/stdc++.h> NEW_LINE using namespace std ; void product_subarrays ( long long int arr [ ] , int n ) { long long int res = 1 ; for ( int i = 0 ; i < n ; i ++ ) { long long int product = 1 ; for ( int j = i ; j < n ; j ++ ) { product = product * arr [ j ] ; res *= product ; } } cout << res << " STRNEWLINE " ; } int main ( ) { long long int arr [ ] = { 10 , 3 , 7 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; product_subarrays ( arr , n ) ; return 0 ; } |
Find numbers that divide X and Y to produce the same remainder | C ++ program to find numbers that divide X and Y to produce the same remainder ; Function to find the required number as M ; Finding the maximum value among X and Y ; Loop to iterate through maximum value among X and Y . ; If the condition satisfies , then print the value of M ; Driver code | #include <iostream> NEW_LINE using namespace std ; void printModulus ( int X , int Y ) { int n = max ( X , Y ) ; for ( int i = 1 ; i <= n ; i ++ ) { if ( X % i == Y % i ) cout << i << " β " ; } } int main ( ) { int X , Y ; X = 10 ; Y = 20 ; printModulus ( X , Y ) ; return 0 ; } |
Find numbers that divide X and Y to produce the same remainder | C ++ program to find numbers that divide X and Y to produce the same remainder ; Function to print all the possible values of M such that X % M = Y % M ; Finding the absolute difference of X and Y ; Iterating from 1 ; Loop to print all the factors of D ; If i is a factor of d , then print i ; If d / i is a factor of d , then print d / i ; Driver code | #include <iostream> NEW_LINE using namespace std ; void printModulus ( int X , int Y ) { int d = abs ( X - Y ) ; int i = 1 ; while ( i * i <= d ) { if ( d % i == 0 ) { cout << i << " β " ; if ( d / i != i ) cout << d / i << " β " ; } i ++ ; } } int main ( ) { int X = 10 ; int Y = 26 ; printModulus ( X , Y ) ; return 0 ; } |
Check whether a number can be represented as difference of two squares | C ++ program to check whether a number can be represented by the difference of two squares ; Function to check whether a number can be represented by the difference of two squares ; Checking if n % 4 = 2 or not ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; bool difSquare ( int n ) { if ( n % 4 != 2 ) { return true ; } return false ; } int main ( ) { int n = 45 ; if ( difSquare ( n ) ) { cout << " Yes STRNEWLINE " ; } else { cout << " No STRNEWLINE " ; } return 0 ; } |
Count of Fibonacci divisors of a given number | C ++ program to count number of divisors of N which are Fibonacci numbers ; Function to create hash table to check Fibonacci numbers ; Function to count number of divisors of N which are fibonacci numbers ; If divisors are equal , check and count only one ; Otherwise check and count both ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; void createHash ( set < int > & hash , int maxElement ) { int prev = 0 , curr = 1 ; hash . insert ( prev ) ; hash . insert ( curr ) ; while ( curr <= maxElement ) { int temp = curr + prev ; hash . insert ( temp ) ; prev = curr ; curr = temp ; } } int countFibonacciDivisors ( int n ) { set < int > hash ; createHash ( hash , n ) ; int cnt = 0 ; for ( int i = 1 ; i <= sqrt ( n ) ; i ++ ) { if ( n % i == 0 ) { if ( ( n / i == i ) && ( hash . find ( n / i ) != hash . end ( ) ) ) cnt ++ ; else { if ( hash . find ( n / i ) != hash . end ( ) ) cnt ++ ; if ( hash . find ( n / ( n / i ) ) != hash . end ( ) ) cnt ++ ; } } } return cnt ; } int main ( ) { int n = 12 ; cout << countFibonacciDivisors ( n ) ; return 0 ; } |
Count of subtrees in a Binary Tree having XOR value K | C ++ program to find the count of subtrees in a Binary Tree having XOR value K ; A binary tree node ; A utility function to allocate a new node ; Base Case : If node is NULL , return 0 ; Calculating the XOR of the current subtree ; Increment res if xr is equal to k ; Return the XOR value of the current subtree ; Function to find the required count ; Initialize result variable ' res ' ; Recursively traverse the tree and compute the count ; return the count ' res ' ; Driver program ; Create the binary tree by adding nodes to it | #include <bits/stdc++.h> NEW_LINE using namespace std ; struct Node { int data ; struct Node * left , * right ; } ; struct Node * newNode ( int data ) { struct Node * newNode = new Node ; newNode -> data = data ; newNode -> left = newNode -> right = NULL ; return ( newNode ) ; } int rec ( Node * root , int & res , int & k ) { if ( root == NULL ) { return 0 ; } int xr = root -> data ; xr ^= rec ( root -> left , res , k ) ; xr ^= rec ( root -> right , res , k ) ; if ( xr == k ) { res ++ ; } return xr ; } int findCount ( Node * root , int K ) { int res = 0 ; rec ( root , res , K ) ; return res ; } int main ( void ) { struct Node * root = newNode ( 2 ) ; root -> left = newNode ( 1 ) ; root -> right = newNode ( 9 ) ; root -> left -> left = newNode ( 10 ) ; root -> left -> right = newNode ( 5 ) ; int K = 5 ; cout << findCount ( root , K ) ; return 0 ; } |
Make array elements equal with minimum cost | C ++ implementation to make array elements equal with minimum cost ; Function to find the minimum cost required to make array elements equal ; Loop to find the count of odd elements ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; void makearrayequal ( int arr [ ] , int n ) { int x = 0 ; for ( int i = 0 ; i < n ; i ++ ) { x += arr [ i ] & 1 ; } cout << min ( x , n - x ) << endl ; } int main ( ) { int arr [ ] = { 4 , 3 , 2 , 1 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; makearrayequal ( arr , n ) ; return 0 ; } |
Count of Prime digits in a Number | C ++ program to count the number of prime digits in a number ; Function to find the count of prime digits in a number ; Loop to compute all the digits of the number ; Finding every digit of the given number ; Checking if digit is prime or not Only 2 , 3 , 5 and 7 are prime one - digit number ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int countDigit ( int n ) { int temp = n , count = 0 ; while ( temp != 0 ) { int d = temp % 10 ; temp /= 10 ; if ( d == 2 d == 3 d == 5 d == 7 ) count ++ ; } return count ; } int main ( ) { int n = 1234567890 ; cout << countDigit ( n ) << endl ; return 0 ; } |
Check if an Array is a permutation of numbers from 1 to N : Set 2 | C ++ program to decide if an array represents a permutation or not ; Function to check if an array represents a permutation or not ; Counting the frequency ; Check if each frequency is 1 only ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; string permutation ( int arr [ ] , int N ) { int hash [ N + 1 ] = { 0 } ; for ( int i = 0 ; i < N ; i ++ ) { hash [ arr [ i ] ] ++ ; } for ( int i = 1 ; i <= N ; i ++ ) { if ( hash [ i ] != 1 ) return " No " ; } return " Yes " ; } int main ( ) { int arr [ ] = { 1 , 1 , 5 , 5 , 3 } ; int n = sizeof ( arr ) / sizeof ( int ) ; cout << permutation ( arr , n ) << endl ; return 0 ; } |
Check if the XOR of an array of integers is Even or Odd | C ++ program to check if the XOR of an array is Even or Odd ; Function to check if the XOR of an array of integers is Even or Odd ; Count the number of odd elements ; If count of odd elements is odd , then XOR will be odd ; Else even ; Driver Code ; Function call | #include <bits/stdc++.h> NEW_LINE using namespace std ; string check ( int arr [ ] , int n ) { int count = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( arr [ i ] & 1 ) count ++ ; } if ( count & 1 ) return " Odd " ; else return " Even " ; } int main ( ) { int arr [ ] = { 3 , 9 , 12 , 13 , 15 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << check ( arr , n ) << endl ; return 0 ; } |
Length of Longest Prime Subsequence in an Array | C ++ program to find the length of Longest Prime Subsequence in an Array ; Function to create Sieve to check primes ; False here indicates that it is not prime ; If prime [ p ] is not changed , then it is a prime ; Update all multiples of p , set them to non - prime ; Function to find the longest subsequence which contain all prime numbers ; Precompute N primes ; Find the length of longest prime subsequence ; Driver code ; Function call | #include <bits/stdc++.h> NEW_LINE using namespace std ; #define N 100005 NEW_LINE void SieveOfEratosthenes ( bool prime [ ] , int p_size ) { prime [ 0 ] = false ; prime [ 1 ] = false ; for ( int p = 2 ; p * p <= p_size ; p ++ ) { if ( prime [ p ] ) { for ( int i = p * 2 ; i <= p_size ; i += p ) prime [ i ] = false ; } } } int longestPrimeSubsequence ( int arr [ ] , int n ) { bool prime [ N + 1 ] ; memset ( prime , true , sizeof ( prime ) ) ; SieveOfEratosthenes ( prime , N ) ; int answer = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( prime [ arr [ i ] ] ) { answer ++ ; } } return answer ; } int main ( ) { int arr [ ] = { 3 , 4 , 11 , 2 , 9 , 21 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << longestPrimeSubsequence ( arr , n ) << endl ; return 0 ; } |
Check if an Octal number is Even or Odd | C ++ code to check if a Octal number is Even or Odd ; Check if the number is odd or even ; Check if the last digit is either '0' , '2' , '4' , or '6' ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; string even_or_odd ( string N ) { int len = N . size ( ) ; if ( N [ len - 1 ] == '0' N [ len - 1 ] == '2' N [ len - 1 ] == '4' N [ len - 1 ] == '6' ) return ( " Even " ) ; else return ( " Odd " ) ; } int main ( ) { string N = "735" ; cout << even_or_odd ( N ) ; return 0 ; } |
Runge | C ++ program to implement Runge Kutta 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 step height h ; Iterate for number of iterations ; Apply Runge Kutta Formulas to find next value of y ; Update next value of y ; Update next value of x ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; float dydx ( float x , float y ) { return ( x + y - 2 ) ; } float rungeKutta ( float x0 , float y0 , float x , float h ) { int n = ( int ) ( ( x - x0 ) / h ) ; float k1 , k2 ; 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 ) ; y = y + ( 1.0 / 6.0 ) * ( k1 + 2 * k2 ) ; x0 = x0 + h ; } return y ; } int main ( ) { float x0 = 0 , y = 1 , x = 2 , h = 0.2 ; cout << fixed << setprecision ( 6 ) << " y ( x ) β = β " << rungeKutta ( x0 , y , x , h ) ; return 0 ; } |
Count of Fibonacci pairs which satisfy the given equation | C ++ program to find the count of Fibonacci pairs ( x , y ) which satisfy the equation Ax + By = N ; Array to store the Fibonacci numbers ; Array to store the number of ordered pairs ; Function to find if a number is a perfect square ; Function that returns 1 if N is non - fibonacci number else 0 ; N is Fibinacci if one of 5 * n * n + 4 or 5 * n * n - 4 or both are perferct square ; Function to store the fibonacci numbers and their frequency in form a * x + b * y ; Storing the Fibonacci numbers ; For loop to find all the possible combinations of the Fibonacci numbers ; Finding the number of ordered pairs ; Driver code ; Find the ordered pair for every query | #include <bits/stdc++.h> NEW_LINE #define size 10001 NEW_LINE using namespace std ; long long fib [ 100010 ] ; int freq [ 100010 ] ; bool isPerfectSquare ( int x ) { int s = sqrt ( x ) ; return ( s * s == x ) ; } int isFibonacci ( int n ) { if ( isPerfectSquare ( 5 * n * n + 4 ) || isPerfectSquare ( 5 * n * n - 4 ) ) return 1 ; return 0 ; } void compute ( int a , int b ) { for ( int i = 1 ; i < 100010 ; i ++ ) { fib [ i ] = isFibonacci ( i ) ; } for ( int x = 1 ; x < 100010 ; x ++ ) { for ( int y = 1 ; y < size ; y ++ ) { if ( fib [ x ] == 1 && fib [ y ] == 1 && a * x + b * y < 100010 ) { freq [ a * x + b * y ] ++ ; } } } } int main ( ) { int Q = 2 , A = 5 , B = 10 ; compute ( A , B ) ; int arr [ Q ] = { 50 , 150 } ; for ( int i = 0 ; i < Q ; i ++ ) { cout << freq [ arr [ i ] ] << " β " ; } return 0 ; } |
Maximise the sum of two Numbers using at most one swap between them | C ++ program to maximise the sum of two Numbers using at most one swap between them ; Function to maximize the sum by swapping only one digit ; Store digits of max ( n1 , n2 ) ; Store digits of min ( n1 , n2 ) ; If length of the two numbers are unequal ; Find the most significant number and the most significant index for swapping ; If both numbers are of equal length ; Fetch the index of current maximum digit present in both the arrays ; Compute the difference ; Find the most significant index and the most significant digit to be swapped ; Restore the new numbers ; Display the maximized sum ; Driver function | #include <bits/stdc++.h> NEW_LINE using namespace std ; #define MAX 100 NEW_LINE void findMaxSum ( int n1 , int n2 ) { int arr1 [ MAX ] = { 0 } , arr2 [ MAX ] = { 0 } ; int l1 = 0 , l2 = 0 ; int max1 = max ( n1 , n2 ) ; int min1 = min ( n1 , n2 ) ; for ( int i = max1 ; i > 0 ; i /= 10 ) arr1 [ l1 ++ ] = ( i % 10 ) ; for ( int i = min1 ; i > 0 ; i /= 10 ) arr2 [ l2 ++ ] = ( i % 10 ) ; int f = 0 ; if ( l1 != l2 ) { int index = ( max_element ( arr2 , arr2 + l2 ) - arr2 ) ; for ( int i = l1 - 1 ; i > ( l2 - 1 ) ; i -- ) { if ( arr1 [ i ] < arr2 [ index ] ) { swap ( arr1 [ i ] , arr2 [ index ] ) ; f = 1 ; break ; } } } if ( f != 1 ) { int index1 = 0 , index2 = 0 ; int diff1 = 0 , diff2 = 0 ; for ( int i = l2 - 1 ; i >= 0 ; i -- ) { index1 = ( max_element ( arr1 , arr1 + i ) - arr1 ) ; index2 = ( max_element ( arr2 , arr2 + i ) - arr2 ) ; diff1 = ( arr2 [ index2 ] - arr1 [ i ] ) ; diff2 = ( arr1 [ index1 ] - arr2 [ i ] ) ; if ( diff1 > 0 diff2 > 0 ) { if ( diff1 > diff2 ) { swap ( arr1 [ i ] , arr2 [ index2 ] ) ; break ; } else if ( diff2 > diff1 ) { swap ( arr2 [ i ] , arr1 [ index1 ] ) ; break ; } else if ( diff1 == diff2 ) { if ( index1 <= index2 ) { swap ( arr2 [ i ] , arr1 [ index1 ] ) ; break ; } else if ( index2 <= index1 ) { swap ( arr1 [ i ] , arr2 [ index2 ] ) ; break ; } } } } } int f_n1 = 0 , f_n2 = 0 ; for ( int i = l1 - 1 ; i >= 0 ; i -- ) { f_n1 = ( f_n1 * 10 ) + arr1 [ i ] ; f_n2 = ( f_n2 * 10 ) + arr2 [ i ] ; } cout << ( f_n1 + f_n2 ) << " STRNEWLINE " ; } int main ( ) { int N1 = 9987 ; int N2 = 123 ; findMaxSum ( N1 , N2 ) ; return 0 ; } |
Check if a number is divisible by 47 or not | C ++ program to check whether a number is divisible by 47 or not ; Function to check if the number is divisible by 47 or not ; While there are at least two digits ; Extracting the last ; Truncating the number ; Subtracting fourteen times the last digit to the remaining number ; Finally return if the two - digit number is divisible by 47 or not ; Driver Code | #include <bits/stdc++.h> NEW_LINE #include <stdlib.h> NEW_LINE using namespace std ; bool isDivisible ( int n ) { int d ; while ( n / 100 ) { d = n % 10 ; n /= 10 ; n = abs ( n - ( d * 14 ) ) ; } return ( n % 47 == 0 ) ; } int main ( ) { int N = 59173 ; if ( isDivisible ( N ) ) cout << " Yes " << endl ; else cout << " No " << endl ; return 0 ; } |
Check if a HexaDecimal number is Even or Odd | C ++ code to check if a HexaDecimal number is Even or Odd ; Check if the number is odd or even ; check if the last digit is either '0' , '2' , '4' , '6' , '8' , ' A ' ( = 10 ) , ' C ' ( = 12 ) or ' E ' ( = 14 ) ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; string even_or_odd ( string N ) { int len = N . size ( ) ; if ( N [ len - 1 ] == '0' N [ len - 1 ] == '2' N [ len - 1 ] == '4' N [ len - 1 ] == '6' N [ len - 1 ] == '8' N [ len - 1 ] == ' A ' N [ len - 1 ] == ' C ' N [ len - 1 ] == ' E ' ) return ( " Even " ) ; else return ( " Odd " ) ; } int main ( ) { string N = " AB3454D " ; cout << even_or_odd ( N ) ; return 0 ; } |
Check if a number is divisible by 31 or not | C ++ program to check whether a number is divisible by 31 or not ; Function to check if the number is divisible by 31 or not ; While there are at least two digits ; Extracting the last ; Truncating the number ; Subtracting three times the last digit to the remaining number ; Finally return if the two - digit number is divisible by 31 or not ; Driver Code | #include <bits/stdc++.h> NEW_LINE #include <stdlib.h> NEW_LINE using namespace std ; bool isDivisible ( int n ) { int d ; while ( n / 100 ) { d = n % 10 ; n /= 10 ; n = abs ( n - ( d * 3 ) ) ; } return ( n % 31 == 0 ) ; } int main ( ) { int N = 1922 ; if ( isDivisible ( N ) ) cout << " Yes " << endl ; else cout << " No " << endl ; return 0 ; } |
Check if the number is divisible 43 or not | C ++ program to check whether a number is divisible by 43 or not ; Function to check if the number is divisible by 43 or not ; While there are at least two digits ; Extracting the last ; Truncating the number ; adding thirteen times the last digit to the remaining number ; Finally return if the two - digit number is divisible by 43 or not ; Driver Code | #include <bits/stdc++.h> NEW_LINE #include <stdlib.h> NEW_LINE using namespace std ; bool isDivisible ( int n ) { int d ; while ( n / 100 ) { d = n % 10 ; n /= 10 ; n = abs ( n + ( d * 13 ) ) ; } return ( n % 43 == 0 ) ; } int main ( ) { int N = 2795 ; if ( isDivisible ( N ) ) cout << " Yes " << endl ; else cout << " No " << endl ; return 0 ; } |
Find the next Non | C ++ implementation of the approach ; Function to check if a number is perfect square ; Function to check if a number is Fibinacci Number ; N is Fibinacci if either ( 5 * N * N + 4 ) , ( 5 * N * N - 4 ) or both is a perferct square ; Function to find the next Non - Fibinacci Number ; Case 1 If N <= 3 , then 4 will be next Non - Fibinacci Number ; Case 2 If N + 1 is Fibinacci , then N + 2 will be next Non - Fibinacci Number ; If N + 1 is Non - Fibinacci , then N + 2 will be next Non - Fibinacci Number ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; bool isPerfectSquare ( int x ) { int s = sqrt ( x ) ; return ( s * s == x ) ; } bool isFibonacci ( int N ) { return isPerfectSquare ( 5 * N * N + 4 ) || isPerfectSquare ( 5 * N * N - 4 ) ; } int nextNonFibonacci ( int N ) { if ( N <= 3 ) return 4 ; if ( isFibonacci ( N + 1 ) ) return N + 2 ; else return N + 1 ; } int main ( ) { int N = 3 ; cout << nextNonFibonacci ( N ) << endl ; N = 5 ; cout << nextNonFibonacci ( N ) << endl ; N = 7 ; cout << nextNonFibonacci ( N ) << endl ; } |
Represent K ^ N as the sum of exactly N numbers | C ++ program to represent K ^ N as the sum of exactly N numbers ; Function to print N numbers whose sum is a power of K ; Printing K ^ 1 ; Loop to print the difference of powers from K ^ 2 ; Driver code | #include <bits/stdc++.h> NEW_LINE #define ll long long int NEW_LINE using namespace std ; void print ( ll n , ll k ) { cout << k << " β " ; for ( int i = 2 ; i <= n ; i ++ ) { ll x = pow ( k , i ) - pow ( k , i - 1 ) ; cout << x << " β " ; } } int main ( ) { ll N = 3 , K = 4 ; print ( N , K ) ; return 0 ; } |
Check if the given number is divisible by 71 or not | C ++ program to check whether a number is divisible by 71 or not ; Function to check if the number is divisible by 71 or not ; While there are at least two digits ; Extracting the last ; Truncating the number ; Subtracting seven times the last digit to the remaining number ; Finally return if the two - digit number is divisible by 71 or not ; Driver Code | #include <bits/stdc++.h> NEW_LINE #include <stdlib.h> NEW_LINE using namespace std ; bool isDivisible ( int n ) { int d ; while ( n / 100 ) { d = n % 10 ; n /= 10 ; n = abs ( n - ( d * 7 ) ) ; } return ( n % 71 == 0 ) ; } int main ( ) { int N = 5041 ; if ( isDivisible ( N ) ) cout << " Yes " << endl ; else cout << " No " << endl ; return 0 ; } |
Count of prime digits of a Number which divides the number | C ++ program to count number of digits which is prime and also divides number ; Function to find the number of digits in number which divides the number and is also a prime number ; Only 2 , 3 , 5 and 7 are prime one - digit number ; Loop to compute all the digits of the number untill it is not equal to the zero ; Fetching each digit of the number ; Checking if digit is greater than 0 and can divides n and is prime too ; Driven Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int countDigit ( int n ) { bool prime [ 10 ] ; memset ( prime , false , sizeof ( prime ) ) ; prime [ 2 ] = prime [ 3 ] = true ; prime [ 5 ] = prime [ 7 ] = true ; int temp = n , count = 0 ; while ( temp != 0 ) { int d = temp % 10 ; temp /= 10 ; if ( d > 0 && n % d == 0 && prime [ d ] ) count ++ ; } return count ; } int main ( ) { int n = 1032 ; cout << countDigit ( n ) << endl ; return 0 ; } |
Bitwise Operations on Digits of a Number | C ++ implementation of the approach ; Function to find the digits ; Function to Find OR of all digits of a number ; Find OR of all digits ; return OR of digits ; Function to Find AND of all digits of a number ; Find AND of all digits ; return AND of digits ; Function to Find XOR of all digits of a number ; Find XOR of all digits ; return XOR of digits ; Driver code ; Find and store all digits ; Find XOR of digits ; Find OR of digits ; Find AND of digits ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int digit [ 100000 ] ; int findDigits ( int n ) { int count = 0 ; while ( n != 0 ) { digit [ count ] = n % 10 ; n = n / 10 ; ++ count ; } return count ; } int OR_of_Digits ( int n , int count ) { int ans = 0 ; for ( int i = 0 ; i < count ; i ++ ) { ans = ans | digit [ i ] ; } return ans ; } int AND_of_Digits ( int n , int count ) { int ans = 0 ; for ( int i = 0 ; i < count ; i ++ ) { ans = ans & digit [ i ] ; } return ans ; } int XOR_of_Digits ( int n , int count ) { int ans = 0 ; for ( int i = 0 ; i < count ; i ++ ) { ans = ans ^ digit [ i ] ; } return ans ; } void bitwise_operation ( int N ) { int countOfDigit = findDigits ( N ) ; cout << " XOR β = β " << XOR_of_Digits ( N , countOfDigit ) << endl ; cout << " OR β = β " << OR_of_Digits ( N , countOfDigit ) << endl ; cout << " AND β = β " << AND_of_Digits ( N , countOfDigit ) << endl ; } int main ( ) { int N = 123456 ; bitwise_operation ( N ) ; return 0 ; } |
Length of longest subarray with product greater than or equal to 0 | C ++ implementation of the above approach ; Function that count the length of longest subarray with product greater than or equals to zero ; If product is greater than zero , return array size ; Traverse the array and if any negative element found then update the length of longest subarray with the length of left and right subarray ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int maxLength ( int arr [ ] , int N ) { int product = 1 , len = 0 ; for ( int i = 0 ; i < N ; i ++ ) { product *= arr [ i ] ; } if ( product >= 0 ) { return N ; } for ( int i = 0 ; i < N ; i ++ ) { if ( arr [ i ] < 0 ) { len = max ( len , max ( N - i - 1 , i ) ) ; } } return len ; } int main ( ) { int arr [ ] = { -1 , 1 , 1 , -2 , 3 , 2 , -1 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << maxLength ( arr , N ) << endl ; return 0 ; } |
Print a pair of numbers with the given Sum and Product | CPP program to find any pair which has sum S and product P . ; Prints roots of quadratic equation ax * 2 + bx + c = 0 ; calculating the sq root value for b * b - 4 * a * c ; Finding the roots ; Check if the roots are valid or not ; Finding the roots ; Check if the roots are valid or not ; when d < 0 ; No such pair exists in this case ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; void findRoots ( int b , int c ) { int a = 1 ; int d = b * b - 4 * a * c ; double sqrt_val = sqrt ( abs ( d ) ) ; if ( d > 0 ) { double x = - b + sqrt_val ; double y = - b - sqrt_val ; int root1 = ( x ) / ( 2 * a ) ; int root2 = ( y ) / ( 2 * a ) ; if ( root1 + root2 == -1 * b && root1 * root2 == c ) cout << root1 << " , β " << root2 ; else cout << -1 ; } else if ( d == 0 ) { int root = - b / ( 2 * a ) ; if ( root + root == -1 * b && root * root == c ) cout << root << " , β " << root ; else cout << -1 ; } else { cout << -1 ; } cout << endl ; } int main ( ) { int S = 5 , P = 6 ; findRoots ( - S , P ) ; S = 5 , P = 9 ; findRoots ( - S , P ) ; return 0 ; } |
Print N numbers such that their product is a Perfect Cube | C ++ program to find N numbers such that their product is a perfect cube ; Function to find the N numbers such that their product is a perfect cube ; Loop to traverse each number from 1 to N ; Print the cube of i as the ith term of the output ; Driver Code ; Function Call | #include <bits/stdc++.h> NEW_LINE using namespace std ; void findNumbers ( int N ) { int i = 1 ; while ( i <= N ) { cout << ( i * i * i ) << " β " ; i ++ ; } } int main ( ) { int N = 4 ; findNumbers ( N ) ; } |
Sum of all proper divisors from 1 to N | C ++ implementation to find sum of all proper divisor of number up to N ; Utility function to find sum of all proper divisor of number up to N ; Loop to iterate over all the numbers from 1 to N ; Find all divisors of i and add them ; Subtracting ' i ' so that the number itself is not included ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int properDivisorSum ( int n ) { int sum = 0 ; for ( int i = 1 ; i <= n ; ++ i ) { for ( int j = 1 ; j * j <= i ; ++ j ) { if ( i % j == 0 ) { if ( i / j == j ) sum += j ; else sum += j + i / j ; } } sum = sum - i ; } return sum ; } int main ( ) { int n = 4 ; cout << properDivisorSum ( n ) << endl ; n = 5 ; cout << properDivisorSum ( n ) << endl ; return 0 ; } |
Sum of all proper divisors from 1 to N | C ++ implementation to find sum of all proper divisor of numbers up to N ; Utility function to find sum of all proper divisor of number up to N ; Loop to find the proper divisor of every number from 1 to N ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int properDivisorSum ( int n ) { int sum = 0 ; for ( int i = 1 ; i <= n ; ++ i ) sum += ( n / i ) * i ; return sum - n * ( n + 1 ) / 2 ; } int main ( ) { int n = 4 ; cout << properDivisorSum ( n ) << endl ; n = 5 ; cout << properDivisorSum ( n ) << endl ; return 0 ; } |
Minimum change in given value so that it lies in all given Ranges | C ++ implementation find the minimum difference in the number D such that D is inside of every range ; Function to find the minimum difference in the number D such that D is inside of every range ; Loop to find the common range out of the given array of ranges . ; Storing the start and end index ; Sorting the range ; Finding the maximum starting value of common segment ; Finding the minimum ending value of common segment ; If there is no common segment ; If the given number is between the computed common range . ; Finding the minimum distance ; Driver Code ; Given array of ranges | #include <bits/stdc++.h> NEW_LINE using namespace std ; void findMinimumOperation ( int n , int d , int arrays [ 3 ] [ 2 ] ) { int cnt = 0 ; int first = INT_MIN , end = INT_MAX ; while ( n -- ) { int arr [ 2 ] = { arrays [ cnt ] [ 0 ] , arrays [ cnt ] [ 1 ] } ; sort ( arr , arr + 2 ) ; first = max ( first , arr [ 0 ] ) ; end = min ( end , arr [ 1 ] ) ; cnt ++ ; } if ( first > end ) cout << " - 1" ; else { if ( d >= first && d <= end ) { cout << "0" ; } else cout << min ( abs ( first - d ) , abs ( d - end ) ) ; } } int main ( ) { int n = 3 , d = 3 ; int arrays [ 3 ] [ 2 ] = { { 0 , 7 } , { 2 , 14 } , { 4 , 6 } } ; findMinimumOperation ( n , d , arrays ) ; } |
Number of factors of very large number N modulo M where M is any prime number | C ++ implementation to find the Number of factors of very large number N modulo M ; Function for modular multiplication ; Function to find the number of factors of large Number N ; Count the number of times 2 divides the number N ; Condition to check if 2 divides it ; Check for all the possible numbers that can divide it ; Loop to check the number of times prime number i divides it ; Condition to check if prime number i divides it ; Condition to check if N at the end is a prime number . ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; #define ll long long NEW_LINE ll mod = 1000000007 ; ll mult ( ll a , ll b ) { return ( ( a % mod ) * ( b % mod ) ) % mod ; } ll calculate_factors ( ll n ) { ll ans , cnt ; cnt = 0 ; ans = 1 ; while ( n % 2 == 0 ) { cnt ++ ; n = n / 2 ; } if ( cnt ) { ans = mult ( ans , ( cnt + 1 ) ) ; } for ( int i = 3 ; i <= sqrt ( n ) ; i += 2 ) { cnt = 0 ; while ( n % i == 0 ) { cnt ++ ; n = n / i ; } if ( cnt ) { ans = mult ( ans , ( cnt + 1 ) ) ; } } if ( n > 2 ) { ans = mult ( ans , ( 2 ) ) ; } return ans % mod ; } int main ( ) { ll n = 193748576239475639 ; mod = 17 ; cout << calculate_factors ( n ) << endl ; return 0 ; } |
Maximum value of B less than A such that A ^ B = A + B | C ++ implementation to find maximum value of B such that A ^ B = A + B ; Function to find the maximum value of B such that A ^ B = A + B ; Binary Representation of A ; Loop to find the negation of the integer A ; Output ; Driver code ; Function Call | #include <bits/stdc++.h> NEW_LINE using namespace std ; void maxValue ( int a ) { string c = bitset < 3 > ( a ) . to_string ( ) ; string b = " " ; for ( int i = 0 ; i < c . length ( ) ; i ++ ) { if ( ( c [ i ] - '0' ) == 1 ) b += '0' ; else b += '1' ; } cout << bitset < 3 > ( b ) . to_ulong ( ) ; } int main ( ) { int a = 4 ; maxValue ( a ) ; return 0 ; } |
Print all possible pair with prime XOR in the Array | C ++ implementation of the above approach ; Function for Sieve of Eratosthenes ; If i is prime , then make all multiples of i false ; Function to print all Pairs whose XOR is prime ; if A [ i ] ^ A [ j ] is prime , then print this pair ; Driver Code ; Generate all the prime number ; Function Call | #include <bits/stdc++.h> NEW_LINE using namespace std ; const int sz = 1e5 ; bool isPrime [ sz + 1 ] ; void generatePrime ( ) { int i , j ; memset ( isPrime , true , sizeof ( isPrime ) ) ; isPrime [ 0 ] = isPrime [ 1 ] = false ; for ( i = 2 ; i * i <= sz ; i ++ ) { if ( isPrime [ i ] ) { for ( j = i * i ; j < sz ; j += i ) { isPrime [ j ] = false ; } } } } void Pair_of_PrimeXor ( int A [ ] , int n ) { for ( int i = 0 ; i < n ; i ++ ) { for ( int j = i + 1 ; j < n ; j ++ ) { if ( isPrime [ ( A [ i ] ^ A [ j ] ) ] ) { cout << " ( " << A [ i ] << " , β " << A [ j ] << " ) β " ; } } } } int main ( ) { int A [ ] = { 1 , 3 , 6 , 11 } ; int n = sizeof ( A ) / sizeof ( A [ 0 ] ) ; generatePrime ( ) ; Pair_of_PrimeXor ( A , n ) ; return 0 ; } |
Check if N can be expressed as product of 3 distinct numbers | C ++ program to find the three numbers ; function to find 3 distinct number with given product ; Declare a vector to store divisors ; store all divisors of number in array ; store all the occurence of divisors ; check if n is not equals to - 1 then n is also a prime factor ; Initialize the variables with 1 ; check for first number a ; check for second number b ; check for third number c ; check for all unwanted condition ; Driver function | #include " bits / stdc + + . h " NEW_LINE using namespace std ; void getnumbers ( int n ) { vector < int > divisor ; for ( int i = 2 ; i * i <= n ; i ++ ) { while ( n % i == 0 ) { divisor . push_back ( i ) ; n /= i ; } } if ( n != 1 ) { divisor . push_back ( n ) ; } int a , b , c , size ; a = b = c = 1 ; size = divisor . size ( ) ; for ( int i = 0 ; i < size ; i ++ ) { if ( a == 1 ) { a = a * divisor [ i ] ; } else if ( b == 1 b == a ) { b = b * divisor [ i ] ; } else { c = c * divisor [ i ] ; } } if ( a == 1 b == 1 c == 1 a == b b == c a == c ) { cout << " - 1" << endl ; } else { cout << a << ' β ' << b << ' β ' << c << endl ; } } int main ( ) { int n = 64 ; getnumbers ( n ) ; } |
Check if all Prime factors of number N are unique or not | C ++ program for the above approach ; Function that returns the all the distinct prime factors in a vector ; If n is divisible by 2 ; Divide n till all factors of 2 ; Check for the prime numbers other than 2 ; Store i in Prime [ ] i is a factor of n ; Divide n till all factors of i ; If n is greater than 2 , then n is prime number after n divided by all factors ; Returns the vector Prime ; Function that check whether N is the product of distinct prime factors or not ; Returns the vector to store all the distinct prime factors ; To find the product of all distinct prime factors ; Find the product ; If product is equals to N , print YES , else print NO ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; vector < int > primeFactors ( int n ) { int i , j ; vector < int > Prime ; if ( n % 2 == 0 ) { Prime . push_back ( 2 ) ; } while ( n % 2 == 0 ) { n = n / 2 ; } for ( i = 3 ; i <= sqrt ( n ) ; i = i + 2 ) { if ( n % i == 0 ) { Prime . push_back ( i ) ; } while ( n % i == 0 ) { n = n / i ; } } if ( n > 2 ) { Prime . push_back ( n ) ; } return Prime ; } void checkDistinctPrime ( int n ) { vector < int > Prime = primeFactors ( n ) ; int product = 1 ; for ( auto i : Prime ) { product *= i ; } if ( product == n ) cout << " YES " ; else cout << " NO " ; } int main ( ) { int N = 30 ; checkDistinctPrime ( N ) ; return 0 ; } |
Count perfect power of K in a range [ L , R ] | C ++ implementation to find the count of numbers those are powers of K in range L to R ; Function to find the Nth root of the number ; initially guessing a random number between 0 to 9 ; Smaller eps , denotes more accuracy ; Initializing difference between two roots by INT_MAX ; xK denotes current value of x ; loop until we reach desired accuracy ; calculating current value from previous value ; Function to count the perfect powers of K in range L to R ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; double nthRoot ( int A , int N ) { double xPre = rand ( ) % 10 ; double eps = 1e-3 ; double delX = INT_MAX ; double xK ; while ( delX > eps ) { xK = ( ( N - 1.0 ) * xPre + ( double ) A / pow ( xPre , N - 1 ) ) / ( double ) N ; delX = abs ( xK - xPre ) ; xPre = xK ; } return xK ; } int countPowers ( int a , int b , int k ) { return ( floor ( nthRoot ( b , k ) ) - ceil ( nthRoot ( a , k ) ) + 1 ) ; } int main ( ) { int a = 7 , b = 28 , k = 2 ; cout << " Count β of β Powers β is β " << countPowers ( a , b , k ) ; return 0 ; } |
Minimum number of primes required such that their sum is equal to N | C ++ program for the above approach ; Function to check if n is prime ; Function to count the minimum prime required for given sum N ; Case 1 : ; Case 2 : ; Case 3 : ; Case 3 a : ; Case 3 b : ; Driver Code ; Function Call | #include <bits/stdc++.h> NEW_LINE using namespace std ; bool isPrime ( int n ) { for ( int i = 2 ; i * i <= n ; i ++ ) { if ( n % i == 0 ) { return false ; } } return true ; } void printMinCountPrime ( int N ) { int minCount ; if ( isPrime ( N ) ) { minCount = 1 ; } else if ( N % 2 == 0 ) { minCount = 2 ; } else { if ( isPrime ( N - 2 ) ) { minCount = 2 ; } else { minCount = 3 ; } } cout << minCount << endl ; } int main ( ) { int N = 100 ; printMinCountPrime ( N ) ; return 0 ; } |
Long Division Method to find Square root with Examples | C ++ program to find the square root of a number by using long division method ; Function to find the square root of a number by using long division method ; int i = 0 , udigit , j ; Loop counters ; Dividing the number into segments ; Last index of the array of segments ; Start long division from the last segment ( j = i ) ; Initialising the remainder to the maximum value ; Including the next segment in new dividend ; Loop to check for the perfect square closest to each segment ; This condition is to find the divisor after adding a digit in the range 0 to 9 ; Calculating the remainder ; Updating the units digit of the quotient ; Adding units digit to the quotient ; New divisor is two times quotient ; Including the remainder in new dividend ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; #define INFINITY_ 9999999 NEW_LINE int sqrtByLongDivision ( int n ) { int cur_divisor = 0 ; int quotient_units_digit = 0 ; int cur_quotient = 0 ; int cur_dividend = 0 ; int cur_remainder = 0 ; int a [ 10 ] = { 0 } ; while ( n > 0 ) { a [ i ] = n % 100 ; n = n / 100 ; i ++ ; } i -- ; for ( j = i ; j >= 0 ; j -- ) { cur_remainder = INFINITY_ ; cur_dividend = cur_dividend * 100 + a [ j ] ; for ( udigit = 0 ; udigit <= 9 ; udigit ++ ) { if ( cur_remainder >= cur_dividend - ( ( cur_divisor * 10 + udigit ) * udigit ) && cur_dividend - ( ( cur_divisor * 10 + udigit ) * udigit ) >= 0 ) { cur_remainder = cur_dividend - ( ( cur_divisor * 10 + udigit ) * udigit ) ; quotient_units_digit = udigit ; } } cur_quotient = cur_quotient * 10 + quotient_units_digit ; cur_divisor = cur_quotient * 2 ; cur_dividend = cur_remainder ; } return cur_quotient ; } int main ( ) { int x = 1225 ; cout << sqrtByLongDivision ( x ) << endl ; return 0 ; } |
Count of consecutive Fibonacci pairs in the given Array | C ++ implementation to count the consecutive fibonacci pairs in the array ; Function to find the previous fibonacci for the number N ; Function to find the next fibonacci number for the number N ; Function to check that a Number is a perfect square or not ; Function to check that a number is fibonacci number or not ; N is Fibinacci if one of ( 5 * n * n + 4 ) or ( 5 * n * n - 4 ) is a perferct square ; Function to count the fibonacci pairs in the array ; Loop to iterate over the array to choose all pairs of the array ; Condition to check if both the number of pair is a fibonacci number ; Condition to check if both the number form consecutive fibonacci numbers ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int previousFibonacci ( int n ) { double a = n / ( ( 1 + sqrt ( 5 ) ) / 2.0 ) ; return round ( a ) ; } int nextFibonacci ( int n ) { double a = n * ( 1 + sqrt ( 5 ) ) / 2.0 ; return round ( a ) ; } bool isPerfectSquare ( int x ) { int s = sqrt ( x ) ; return ( s * s == x ) ; } bool isFibonacci ( int n ) { return ( isPerfectSquare ( 5 * n * n + 4 ) || isPerfectSquare ( 5 * n * n - 4 ) ) ; } int countFibonacciPairs ( int arr [ ] , int n ) { int res = 0 ; for ( int i = 0 ; i < n ; i ++ ) for ( int j = i + 1 ; j < n ; j ++ ) if ( isFibonacci ( arr [ i ] ) && isFibonacci ( arr [ j ] ) ) { int prevFib = previousFibonacci ( arr [ i ] ) ; int nextFib = nextFibonacci ( arr [ i ] ) ; if ( prevFib == arr [ j ] nextFib == arr [ j ] ) { res ++ ; } } return res ; } int main ( ) { int a [ ] = { 3 , 5 , 8 , 11 } ; int n = sizeof ( a ) / sizeof ( a [ 0 ] ) ; cout << countFibonacciPairs ( a , n ) ; return 0 ; } |
Count all distinct pairs with product equal to K | C ++ program to count the number of pairs whose product is equal to K ; Function to count the number of pairs whose product is equal to K ; Pick all elements one by one ; Check if the product of this pair is equal to K ; Driver code | #include <iostream> NEW_LINE using namespace std ; int countPairsWithProdK ( int arr [ ] , int n , int k ) { int count = 0 ; for ( int i = 0 ; i < n ; i ++ ) { for ( int j = i + 1 ; j < n ; j ++ ) if ( arr [ i ] * arr [ j ] == k ) count ++ ; } return count ; } int main ( ) { int arr [ ] = { 1 , 5 , 3 , 4 , 2 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; int K = 3 ; cout << countPairsWithProdK ( arr , N , K ) ; return 0 ; } |
Count all distinct pairs with product equal to K | C ++ program to count the number of pairs whose product is equal to K ; Function to count the number of pairs whose product is equal to K ; Initialize the count ; Initialize empty hashmap . ; Insert array elements to hashmap ; Checking if the index is a whole number and present in the hashmap ; Driver code | #include <algorithm> NEW_LINE #include <iostream> NEW_LINE using namespace std ; #define MAX 100000 NEW_LINE int countPairsWithProductK ( int arr [ ] , int n , int k ) { int count = 0 ; bool hashmap [ MAX ] = { false } ; for ( int i = 0 ; i < n ; i ++ ) hashmap [ arr [ i ] ] = true ; for ( int i = 0 ; i < n ; i ++ ) { int x = arr [ i ] ; double index = 1.0 * k / arr [ i ] ; if ( index >= 0 && ( ( index - ( int ) ( index ) ) == 0 ) && hashmap [ k / x ] ) count ++ ; hashmap [ x ] = false ; } return count ; } int main ( ) { int arr [ ] = { 1 , 5 , 3 , 4 , 2 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; int K = 3 ; cout << countPairsWithProductK ( arr , N , K ) ; return 0 ; } |
Find any K distinct odd integers such that their sum is equal to N | C ++ implementation to find k odd integers such that their sum is N ; Function to find K odd integers such that their sum is N ; Condition to check if there exist such K integers ; Loop to find first K - 1 distinct odd integers ; Final Kth odd number ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; void oddIntegers ( int n , int k ) { if ( n % 2 != k % 2 ) { cout << " - 1" << " STRNEWLINE " ; return ; } int sum = 0 ; int i = 1 ; int j = 1 ; while ( j < k ) { sum = sum + i ; cout << i << " β " ; i = i + 2 ; j ++ ; } int finalOdd = n - sum ; cout << finalOdd << " STRNEWLINE " ; } int main ( ) { int n = 10 ; int k = 2 ; oddIntegers ( n , k ) ; return 0 ; } |
Sum of product of proper divisors of all Numbers lying in range [ L , R ] | C ++ implementation to find the sum of the product of proper divisors of all the numbers lying in the range [ L , R ] ; Vector to store the product of the proper divisors of a number ; Variable to store the prefix sum of the product array ; Function to precompute the product of proper divisors of a number at it 's corresponding index ; Modificatino of sieve to store the product of the proper divisors ; Multiplying the existing value with i because i is the proper divisor of ans [ j ] ; Loop to store the prefix sum of the previously computed product array ; Computing the prefix sum ; Function to print the sum for each query ; Function to print te sum of product of proper divisors of a number in [ L , R ] ; Calling the function that pre computes the sum of product of proper divisors ; Iterate over all Queries to print the sum ; Driver code | #include <bits/stdc++.h> NEW_LINE #define ll long long int NEW_LINE #define mod 1000000007 NEW_LINE using namespace std ; vector < ll > ans ( 100002 , 1 ) ; long long pref [ 100002 ] ; void preCompute ( ) { for ( int i = 2 ; i <= 100000 / 2 ; i ++ ) { for ( int j = 2 * i ; j <= 100000 ; j += i ) { ans [ j ] = ( ans [ j ] * i ) % mod ; } } for ( int i = 1 ; i < 100002 ; ++ i ) { pref [ i ] = pref [ i - 1 ] + ans [ i ] ; pref [ i ] %= mod ; } } void printSum ( int L , int R ) { cout << pref [ R ] - pref [ L - 1 ] << " β " ; } void printSumProper ( int arr [ ] [ 2 ] , int Q ) { preCompute ( ) ; for ( int i = 0 ; i < Q ; i ++ ) { printSum ( arr [ i ] [ 0 ] , arr [ i ] [ 1 ] ) ; } } int main ( ) { int Q = 2 ; int arr [ ] [ 2 ] = { { 10 , 20 } , { 12 , 16 } } ; printSumProper ( arr , Q ) ; return 0 ; } |
Generate an array of size N according to the given rules | C ++ implementation to generate an array of size N by following the given rules ; Function to search the most recent location of element N If not present in the array it will return - 1 ; Function to generate an array of size N by following the given rules ; Loop to fill the array as per the given rules ; Check for the occurrence of arr [ i - 1 ] ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int search ( int a [ ] , int k , int x ) { int j ; for ( j = k - 1 ; j > -1 ; j -- ) { if ( a [ j ] == x ) return j ; } return -1 ; } void genArray ( int arr [ ] , int N ) { for ( int i = 0 ; i < N - 1 ; i ++ ) { if ( search ( arr , i , arr [ i ] ) == -1 ) arr [ i + 1 ] = 0 ; else arr [ i + 1 ] = ( i - search ( arr , i , arr [ i ] ) ) ; } } int main ( ) { int N = 5 ; int size = N + 1 ; int a [ ] = { 0 , 0 , 0 , 0 , 0 } ; genArray ( a , N ) ; for ( int i = 0 ; i < N ; i ++ ) cout << a [ i ] << " β " ; return 0 ; } |
Count of pairs in an Array whose sum is a Perfect Cube | C ++ implementation of the approach ; Function to return an ArrayList containing all the perfect cubes upto n ; while current perfect cube is less than or equal to n ; Function to print the sum of maximum two elements from the array ; Function to return the count of numbers that when added with n give a perfect cube ; temp > n is checked so that pairs ( x , y ) and ( y , x ) don 't get counted twice ; Function to count the pairs whose sum is a perfect cube ; Sum of the maximum two elements from the array ; List of perfect cubes upto max ; Contains all the array elements ; Add count of the elements that when added with arr [ i ] give a perfect cube ; Driver code | #include <bits/stdc++.h> NEW_LINE #include <vector> NEW_LINE using namespace std ; vector < int > getPerfectcubes ( int n ) { vector < int > perfectcubes ; int current = 1 ; int i = 1 ; while ( current <= n ) { perfectcubes . push_back ( current ) ; i += 1 ; current = int ( pow ( i , 3 ) ) ; } return perfectcubes ; } int maxPairSum ( int arr [ ] , int n ) { int max = 0 ; int secondMax = 0 ; if ( arr [ 0 ] > arr [ 1 ] ) { max = arr [ 0 ] ; secondMax = arr [ 1 ] ; } else { max = arr [ 1 ] ; secondMax = arr [ 0 ] ; } for ( int i = 2 ; i < n ; i ++ ) { if ( arr [ i ] > max ) { secondMax = max ; max = arr [ i ] ; } else if ( arr [ i ] > secondMax ) secondMax = arr [ i ] ; } return ( max + secondMax ) ; } int countPairsWith ( int n , vector < int > perfectcubes , vector < int > nums ) { int count = 0 ; int len = perfectcubes . size ( ) ; for ( int i = 0 ; i < len ; i ++ ) { int temp = perfectcubes [ i ] - n ; if ( temp > n ) { for ( auto j = nums . begin ( ) ; j != nums . end ( ) ; j ++ ) { if ( ( * j ) == temp ) count += 1 ; } } } return count ; } int countPairs ( int arr [ ] , int n ) { int max = maxPairSum ( arr , n ) ; vector < int > perfectcubes = getPerfectcubes ( max ) ; vector < int > nums ; for ( int i = 0 ; i < n ; i ++ ) nums . push_back ( arr [ i ] ) ; int count = 0 ; for ( int i = 0 ; i < n ; i ++ ) { count += countPairsWith ( arr [ i ] , perfectcubes , nums ) ; } return count ; } int main ( ) { int arr [ ] = { 2 , 6 , 18 , 9 , 999 , 1 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << ( countPairs ( arr , n ) ) ; } |
Maximum Squares possible parallel to both axes from N distinct points | C ++ implementation of the approach ; Function that returns the count of squares parallel to both X and Y - axis from a given set of points ; Initialize result ; Initialize a set to store points ; Initialize a map to store the points in the same vertical line ; Store the points in a set ; Store the points in the same vertical line i . e . with same X co - ordinates ; Check for every two points in the same vertical line ; Check if other two point are present or not ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int countSquares ( int * X , int * Y , int N ) { int count = 0 ; set < pair < int , int > > points ; map < int , vector < int > > vertical ; for ( int i = 0 ; i < N ; i ++ ) { points . insert ( { X [ i ] , Y [ i ] } ) ; } for ( int i = 0 ; i < N ; i ++ ) { vertical [ X [ i ] ] . push_back ( Y [ i ] ) ; } for ( auto line : vertical ) { int X1 = line . first ; vector < int > yList = line . second ; for ( int i = 0 ; i < yList . size ( ) ; i ++ ) { int Y1 = yList [ i ] ; for ( int j = i + 1 ; j < yList . size ( ) ; j ++ ) { int Y2 = yList [ j ] ; int side = abs ( Y1 - Y2 ) ; int X2 = X1 + side ; if ( points . find ( { X2 , Y1 } ) != points . end ( ) and points . find ( { X2 , Y2 } ) != points . end ( ) ) count ++ ; } } } return count ; } int main ( ) { int X [ ] = { 0 , 2 , 0 , 2 } , Y [ ] = { 0 , 2 , 2 , 0 } ; int N = sizeof ( X ) / sizeof ( X [ 0 ] ) ; cout << countSquares ( X , Y , N ) ; return 0 ; } |
Number of perfect cubes between two given numbers | A Simple Method to count cubes between a and b ; Function to count cubes between two numbers ; Traverse through all numbers ; Check if current number ' i ' is perfect cube ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int countCubes ( int a , int b ) { for ( int i = a ; i <= b ; i ++ ) for ( int j = 1 ; j * j * j <= i ; j ++ ) if ( j * j * j == i ) cnt ++ ; return cnt ; } int main ( ) { int a = 7 , b = 30 ; cout << " Count β of β Cubes β is β " << countCubes ( a , b ) ; return 0 ; } |
Number of perfect cubes between two given numbers | An Efficient Method to count cubes between a and b ; Function to count cubes between two numbers ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int countCubes ( int a , int b ) { return ( floor ( cbrt ( b ) ) - ceil ( cbrt ( a ) ) + 1 ) ; } int main ( ) { int a = 7 , b = 28 ; cout << " Count β of β cubes β is β " << countCubes ( a , b ) ; return 0 ; } |
XOR and OR of all N | C ++ program to find the XOR and OR of all Armstrong numbers of N digits ; Function to check if a number is Armstrong or not ; Function to find XOR of all N - digits Armstrong number ; To store the XOR and OR of all Armstrong number ; Starting N - digit Armstrong number ; Ending N - digit Armstrong number ; Iterate over starting and ending number ; To check if i is Armstrong or not ; Print the XOR and OR of all Armstrong number ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; bool isArmstrong ( int x , int n ) { int sum1 = 0 ; int temp = x ; while ( temp > 0 ) { int digit = temp % 10 ; sum1 += ( int ) pow ( digit , n ) ; temp /= 10 ; } return sum1 == x ; } void CalculateXORandOR ( int n ) { int CalculateXOR = 0 ; int CalculateOR = 0 ; int start = ( int ) pow ( 10 , n - 1 ) ; int end = ( int ) pow ( 10 , n ) - 1 ; for ( int i = start ; i < end + 1 ; i ++ ) { if ( isArmstrong ( i , n ) ) { CalculateXOR = CalculateXOR ^ i ; CalculateOR = CalculateOR | i ; } } cout << " XOR β = β " << CalculateXOR << endl ; cout << " OR β = β " << CalculateOR << endl ; } int main ( ) { int n = 4 ; CalculateXORandOR ( n ) ; } |
Perfect Cube | C ++ program to check whether the given number N is the perfect cube or not ; Function to check if a number is a perfect Cube or not ; Iterate from 1 - N ; Find the cube of every number ; Check if cube equals N or not ; Driver code ; Function call | . #include <bits/stdc++.h> NEW_LINE using namespace std ; void perfectCube ( int N ) { int cube ; for ( int i ; i <= N ; i ++ ) { cube = i * i * i ; if ( cube == N ) { cout << " Yes " ; return ; } else if ( cube > N ) { cout << " NO " ; return ; } } } int main ( ) { int N = 216 ; perfectCube ( N ) ; return 0 ; } |
Perfect Cube | C ++ program to check whether the given number N is the perfect cube or not ; Function to check if a number is a perfect Cube using inbuilt function ; If cube of cube_root is equals to N , then print Yes Else print No ; Driver 's code ; Function call to check N is cube or not | #include <bits/stdc++.h> NEW_LINE using namespace std ; void perfectCube ( int N ) { int cube_root ; cube_root = round ( cbrt ( N ) ) ; if ( cube_root * cube_root * cube_root == N ) { cout << " Yes " ; return ; } else { cout << " NO " ; return ; } } int main ( ) { int N = 125 ; perfectCube ( N ) ; return 0 ; } |
Check if given array can be made 0 with given operations performed any number of times | C ++ implementation of the approach ; Function to whether the array can be made zero or not ; Count for even elements ; Count for odd elements ; Traverse the array to count the even and odd ; If arr [ i ] is odd ; If arr [ i ] is even ; Check if count of even is zero or count of odd is zero ; Driver 's Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; bool check ( int arr [ ] , int N ) { int even = 0 ; int odd = 0 ; for ( int i = 0 ; i < N ; i ++ ) { if ( arr [ i ] & 1 ) { odd ++ ; } else { even ++ ; } } if ( even == N odd == N ) cout << " Yes " ; else cout << " No " ; } int main ( ) { int arr [ ] = { 1 , 1 , 3 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; check ( arr , N ) ; return 0 ; } |
Calculate sum of all integers from 1 to N , excluding perfect power of 2 | C ++ implementation of the approach ; Function to find the required summation ; Find the sum of first N integers using the formula ; Find the sum of numbers which are exact power of 2 by using the formula ; Print the final Sum ; Driver 's Code ; Function to find the sum | #include <bits/stdc++.h> NEW_LINE using namespace std ; void findSum ( int N ) { int sum = ( N ) * ( N + 1 ) / 2 ; int r = log2 ( N ) + 1 ; int expSum = pow ( 2 , r ) - 1 ; cout << sum - expSum << endl ; } int main ( ) { int N = 2 ; findSum ( N ) ; return 0 ; } |
Largest Even and Odd N | C ++ implementation of the above approach ; Function to print the largest N - digit even and odd numbers of base B ; Initialise the Number ; If Base B is even , then B ^ n will give largest Even number of N + 1 digit ; To get even number of N digit subtract 2 from B ^ n ; To get odd number of N digit subtract 1 from B ^ n ; If Base B is odd , then B ^ n will give largest Odd number of N + 1 digit ; To get even number of N digit subtract 1 from B ^ n ; To get odd number of N digit subtract 2 from B ^ n ; Driver 's Code ; Function to find the numbers | #include <bits/stdc++.h> NEW_LINE using namespace std ; void findNumbers ( int n , int b ) { int even = 0 , odd = 0 ; if ( b % 2 == 0 ) { even = pow ( b , n ) - 2 ; odd = pow ( b , n ) - 1 ; } else { even = pow ( b , n ) - 1 ; odd = pow ( b , n ) - 2 ; } cout << " Even β Number β = β " << even << ' ' ; cout << " Odd β Number β = β " << odd ; } int main ( ) { int N = 2 , B = 5 ; findNumbers ( N , B ) ; return 0 ; } |
Minimum divisor of a number to make the number perfect cube | C ++ program to find minimum number which divide n to make it a perfect cube ; Returns the minimum divisor ; Since 2 is only even prime , compute its power seprately . ; If count is not divisible by 3 , it must be removed by dividing n by prime number power . ; If count is not divisible by 3 , it must be removed by dividing n by prime number power . ; if n is a prime number ; Driven Program | #include <bits/stdc++.h> NEW_LINE using namespace std ; int findMinNumber ( int n ) { int count = 0 , ans = 1 ; while ( n % 2 == 0 ) { count ++ ; n /= 2 ; } if ( count % 3 != 0 ) ans *= pow ( 2 , ( count % 3 ) ) ; for ( int i = 3 ; i <= sqrt ( n ) ; i += 2 ) { count = 0 ; while ( n % i == 0 ) { count ++ ; n /= i ; } if ( count % 3 != 0 ) ans *= pow ( i , ( count % 3 ) ) ; } if ( n > 2 ) ans *= n ; return ans ; } int main ( ) { int n = 128 ; cout << findMinNumber ( n ) << endl ; return 0 ; } |
Check whether the number can be made perfect square after adding K | C ++ program to check whether the number can be made perfect square after adding K ; Function to check whether the number can be made perfect square after adding K ; Computing the square root of the number ; Print Yes if the number is a perfect square ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; void isPerfectSquare ( long long int x ) { long double sr = round ( sqrt ( x ) ) ; if ( sr * sr == x ) cout << " Yes " ; else cout << " No " ; } int main ( ) { int n = 7 , k = 2 ; isPerfectSquare ( n + k ) ; return 0 ; } |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.