text
stringlengths 17
4.49k
| code
stringlengths 49
5.46k
|
---|---|
Icosikaienneagonal Number | C ++ implementation for above approach ; Function to Find the Nth icosikaienneagonal Number ; Driver Code | #include <iostream> NEW_LINE using namespace std ; int icosikaienneagonalNum ( int n ) { return ( 27 * n * n - 25 * n ) / 2 ; } int main ( ) { int n = 3 ; cout << icosikaienneagonalNum ( n ) ; return 0 ; } |
Find the largest contiguous pair sum in given Array | C ++ program to find the a contiguous pair from the which has the largest sum ; Function to find and return the largest sum contiguous pair ; Stores the contiguous pair ; Initialize maximum sum ; Compare sum of pair with max_sum ; Insert the pair ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; vector < int > largestSumpair ( int arr [ ] , int n ) { vector < int > pair ; int max_sum = INT_MIN , i ; for ( i = 1 ; i < n ; i ++ ) { if ( max_sum < ( arr [ i ] + arr [ i - 1 ] ) ) { max_sum = arr [ i ] + arr [ i - 1 ] ; if ( pair . empty ( ) ) { pair . push_back ( arr [ i - 1 ] ) ; pair . push_back ( arr [ i ] ) ; } else { pair [ 0 ] = arr [ i - 1 ] ; pair [ 1 ] = arr [ i ] ; } } } return pair ; } int main ( ) { int arr [ ] = { 11 , -5 , 9 , -3 , 2 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; vector < int > pair = largestSumpair ( arr , N ) ; for ( auto it = pair . begin ( ) ; it != pair . end ( ) ; ++ it ) { cout << * it << ' β ' ; } return 0 ; } |
Sum of minimum value of x and y satisfying the equation ax + by = c | C ++ program for the above approach ; x and y store solution of equation ax + by = g ; Euclidean Algorithm ; store_gcd returns the gcd of a and b ; Function to find any possible solution ; Condition if solution does not exists ; Adjusting the sign of x0 and y0 ; Function to shift solution ; Shifting to obtain another solution ; Function to find minimum value of x and y ; g is the gcd of a and b ; Store sign of a and b ; If x is less than 0 , then shift solution ; If y is less than 0 , then shift solution ; Find intersection such that both x and y are positive ; miny is value of y corresponding to minx ; Returns minimum value of x + y ; Driver Code ; Given a , b , and c ; Function Call | #include <bits/stdc++.h> NEW_LINE using namespace std ; int gcd ( int a , int b , int * x , int * y ) { if ( b == 0 ) { * x = 1 ; * y = 0 ; return a ; } int x1 , y1 ; int store_gcd = gcd ( b , a % b , & x1 , & y1 ) ; * x = y1 ; * y = x1 - y1 * ( a / b ) ; return store_gcd ; } int possible_solution ( int a , int b , int c , int * x0 , int * y0 , int * g ) { * g = gcd ( fabs ( a ) , fabs ( b ) , x0 , y0 ) ; if ( c % * g ) { return 0 ; } * x0 *= c / * g ; * y0 *= c / * g ; if ( a < 0 ) * x0 *= -1 ; if ( b < 0 ) * y0 *= -1 ; return 1 ; } void shift_solution ( int * x , int * y , int a , int b , int shift_var ) { * x += shift_var * b ; * y -= shift_var * a ; } int find_min_sum ( int a , int b , int c ) { int x , y , g ; if ( ! possible_solution ( a , b , c , & x , & y , & g ) ) return -1 ; a /= g ; b /= g ; int sign_a = a > 0 ? +1 : -1 ; int sign_b = b > 0 ? +1 : -1 ; shift_solution ( & x , & y , a , b , - x / b ) ; if ( x < 0 ) shift_solution ( & x , & y , a , b , sign_b ) ; int minx1 = x ; shift_solution ( & x , & y , a , b , y / a ) ; if ( y < 0 ) shift_solution ( & x , & y , a , b , - sign_a ) ; int minx2 = x ; if ( minx2 > x ) swap ( minx2 , x ) ; int minx = max ( minx1 , minx2 ) ; if ( minx > x ) return -1 ; int miny = ( c - a * x ) / b ; return ( miny + minx ) ; } int main ( ) { int a = 2 , b = 2 , c = 0 ; cout << find_min_sum ( a , b , c ) << " STRNEWLINE " ; return 0 ; } |
Second hexagonal numbers | C ++ implementation to find N - th term in the series ; Function to find N - th term in the series ; Driver code | #include <iostream> NEW_LINE #include <math.h> NEW_LINE using namespace std ; void findNthTerm ( int n ) { cout << n * ( 2 * n + 1 ) << endl ; } int main ( ) { int N = 4 ; findNthTerm ( N ) ; return 0 ; } |
Duffinian Numbers | C ++ program for the above approach ; Function to calculate the sum of all divisors of a given number ; Sum of divisors ; Find all divisors of num ; if ' i ' is divisor of ' n ' ; If both divisors are same then add it once ; Add 1 and n to result as above loop considers proper divisors greater than 1. ; Function to check if n is an Duffinian number ; Calculate the sum of divisors ; If number is prime return false ; Find the gcd of n and sum of divisors of n ; Returns true if N and sumDivisors are relatively prime ; Driver Code ; Given Number ; Function Call | #include <bits/stdc++.h> NEW_LINE using namespace std ; int divSum ( int n ) { int result = 0 ; for ( int i = 2 ; i <= sqrt ( n ) ; i ++ ) { if ( n % i == 0 ) { if ( i == ( n / i ) ) result += i ; else result += ( i + n / i ) ; } } return ( result + n + 1 ) ; } bool isDuffinian ( int n ) { int sumDivisors = divSum ( n ) ; if ( sumDivisors == n + 1 ) return false ; int hcf = __gcd ( n , sumDivisors ) ; return hcf == 1 ; } int main ( ) { int n = 36 ; if ( isDuffinian ( n ) ) cout << " Yes " ; else cout << " No " ; return 0 ; } |
Kummer Numbers | C ++ program to find Kummer number upto n terms ; vector to store all prime less than and equal to 10 ^ 6 ; Function for the Sieve of Sundaram . This function stores all prime numbers less than MAX in primes ; In general Sieve of Sundaram , produces primes smaller than ( 2 * x + 2 ) for a number given number x . Since we want primes smaller than MAX , we reduce MAX to half This array is used to separate numbers of the form i + j + 2 ij from others where 1 <= i <= j ; Main logic of Sundaram . Mark all numbers which do not generate prime number by doing 2 * i + 1 ; Since 2 is a prime number ; Print other primes . Remaining primes are of the form 2 * i + 1 such that marked [ i ] is false . ; Function to calculate nth Kummer number ; Multiply first n primes ; return nth Kummer number ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; const int MAX = 1000000 ; vector < int > primes ; void sieveSundaram ( ) { bool marked [ MAX / 2 + 1 ] = { 0 } ; for ( int i = 1 ; i <= ( sqrt ( MAX ) - 1 ) / 2 ; i ++ ) for ( int j = ( i * ( i + 1 ) ) << 1 ; j <= MAX / 2 ; j += 2 * i + 1 ) marked [ j ] = true ; primes . push_back ( 2 ) ; for ( int i = 1 ; i <= MAX / 2 ; i ++ ) if ( marked [ i ] == false ) primes . push_back ( 2 * i + 1 ) ; } int calculateKummer ( int n ) { int result = 1 ; for ( int i = 0 ; i < n ; i ++ ) result = result * primes [ i ] ; return -1 + result ; } int main ( ) { int n = 5 ; sieveSundaram ( ) ; for ( int i = 1 ; i <= n ; i ++ ) cout << calculateKummer ( i ) << " , β " ; return 0 ; } |
Check if given number contains a digit which is the average of all other digits | C ++ Program to check whether a given number contains a digit which is the average of all other digits ; Function which checks if a digits exists in n which is the average of all other digits ; Calculate sum of digits in n ; Store the digits ; Increase the count of digits in n ; If average of all digits is an integer ; Otherwise ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; void check ( int n ) { set < int > digits ; int temp = n ; int sum = 0 ; int count = 0 ; while ( temp > 0 ) { sum += temp % 10 ; digits . insert ( temp % 10 ) ; count ++ ; temp = temp / 10 ; } if ( sum % count == 0 && digits . find ( sum / count ) != digits . end ( ) ) cout << " Yes " << endl ; else cout << " No " << endl ; } int main ( ) { int n = 42644 ; check ( n ) ; } |
Count of lexicographically smaller characters on right | ; function to count the smaller characters at the right of index i ; store the length of string ; for each index initialize count as zero ; increment the count if characters are smaller than at ith index ; print the count of characters smaller than the index i ; Driver code ; input string | #include <bits/stdc++.h> NEW_LINE using namespace std ; void countSmaller ( string str ) { int n = str . length ( ) ; for ( int i = 0 ; i < n ; i ++ ) { int cnt = 0 ; for ( int j = i + 1 ; j < n ; j ++ ) { if ( str [ j ] < str [ i ] ) { cnt += 1 ; } } cout << cnt << " β " ; } } int main ( ) { string str = " edcba " ; countSmaller ( str ) ; } |
Find the smallest contiguous sum pair in an Array | C ++ program to find the smallest sum contiguous pair ; Function to find the smallest sum contiguous pair ; Contiguous pair ; Initialize minimum sum with maximum value ; Checking for minimum value ; Add to pair ; Updating pair ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; vector < int > smallestSumpair ( int arr [ ] , int n ) { vector < int > pair ; int min_sum = INT_MAX ; for ( int i = 1 ; i < n ; i ++ ) { if ( min_sum > ( arr [ i ] + arr [ i - 1 ] ) ) { min_sum = arr [ i ] + arr [ i - 1 ] ; if ( pair . empty ( ) ) { pair . push_back ( arr [ i - 1 ] ) ; pair . push_back ( arr [ i ] ) ; } else { pair [ 0 ] = arr [ i - 1 ] ; pair [ 1 ] = arr [ i ] ; } } } return pair ; } int main ( ) { int arr [ ] = { 4 , 9 , -3 , 2 , 0 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; vector < int > pair = smallestSumpair ( arr , n ) ; cout << pair [ 0 ] << " β " << pair [ 1 ] ; } |
Add two integers of different base and represent sum in smaller base of the two | Program to find the sum of two integers of different bases . ; Initialize power of base ; Initialize result ; Decimal equivalent is str [ len - 1 ] * 1 + str [ len - 2 ] * base + str [ len - 3 ] * ( base ^ 2 ) + ... ; Maximum base - 36 ; To reverse the string ; Driver Code ; Integer in base 10 ; Sum of integers ; Minimum Base ; Sum of integers in Min Base | #include <bits/stdc++.h> NEW_LINE using namespace std ; int val ( char c ) { if ( c >= '0' && c <= '9' ) return ( int ) c - '0' ; else return ( int ) c - ' A ' + 10 ; } int convert ( string num , int base ) { int len = ( num . size ( ) ) ; int power = 1 ; int res = 0 ; int i ; for ( i = len - 1 ; i >= 0 ; i -- ) { res += val ( num [ i ] ) * power ; power = power * base ; } return res ; } int dec_to_base ( int num , int base ) { string base_num = " " ; while ( num > 0 ) { int dig = int ( num % base ) ; if ( dig < 10 ) base_num += to_string ( dig ) ; else base_num += to_string ( ' A ' + dig - 10 ) ; num /= base ; } reverse ( base_num . begin ( ) , base_num . end ( ) ) ; return stoi ( base_num ) ; } int main ( ) { string a = "123" ; string b = "234" ; int base_a = 6 ; int base_b = 8 ; int a10 = convert ( a , base_a ) ; int b10 = convert ( b , base_b ) ; int summ = a10 + b10 ; int min_base = min ( base_a , base_b ) ; cout << ( dec_to_base ( summ , min_base ) ) ; } |
Sum of the products of same placed digits of two numbers | C ++ program to calculate the sum of same placed digits of two numbers ; Function to find the sum of the products of their corresponding digits ; Loop until one of the numbers have no digits remaining ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int sumOfProductOfDigits ( int n1 , int n2 ) { int sum = 0 ; while ( n1 > 0 && n2 > 0 ) { sum += ( ( n1 % 10 ) * ( n2 % 10 ) ) ; n1 /= 10 ; n2 /= 10 ; } return sum ; } int main ( ) { int n1 = 25 ; int n2 = 1548 ; cout << sumOfProductOfDigits ( n1 , n2 ) ; } |
Print all permutations of a number N greater than itself | C ++ implementation to print all the permutation greater than the integer N ; Function to print all the permutation which are greater than N itself ; Iterate and count the number of digits in N ; vector to print the permutations of N ; Store digits of N in the vector num ; Iterate over every permutation of N which is greater than N ; Print the current permutation of N ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; void printPermutation ( int N ) { int temp = N , count = 0 ; while ( temp > 0 ) { count ++ ; temp /= 10 ; } vector < int > num ( count ) ; while ( N > 0 ) { num [ count -- - 1 ] = N % 10 ; N = N / 10 ; } while ( next_permutation ( num . begin ( ) , num . end ( ) ) ) { for ( int i = 0 ; i < num . size ( ) ; i ++ ) cout << num [ i ] ; cout << " STRNEWLINE " ; } } int main ( ) { int N = 324 ; printPermutation ( N ) ; return 0 ; } |
Count of ways to represent N as sum of a prime number and twice of a square | C ++ implementation to count the number of ways a number can be written as sum of prime number and twice a square ; Function to mark all the prime numbers using sieve ; Initially all the numbers are marked as prime ; Loop to mark the prime numbers upto the Square root of N ; Loop to store the prime numbers in an array ; Function to find the number ways to represent a number as the sum of prime number and square of a number ; Loop to iterate over all the possible prime numbers ; Increment the count if the given number is a valid number ; Driver Code ; Function Call | #include <bits/stdc++.h> NEW_LINE using namespace std ; long long int n = 500000 - 2 ; vector < long long int > v ; void sieveoferanthones ( ) { bool prime [ n + 1 ] ; memset ( prime , true , sizeof ( prime ) ) ; for ( long long int i = 2 ; i <= sqrt ( n ) ; i ++ ) { if ( prime [ i ] ) for ( long long int j = i * i ; j <= n ; j += i ) { prime [ j ] = false ; } } for ( long long int i = 2 ; i < n ; i ++ ) { if ( prime [ i ] ) v . push_back ( i ) ; } } void numberOfWays ( long long int n ) { long long int count = 0 ; for ( long long int j = 1 ; 2 * ( pow ( j , 2 ) ) < n ; j ++ ) { for ( long long int i = 1 ; v [ i ] + 2 <= n ; i ++ ) { if ( n == v [ i ] + ( 2 * ( pow ( j , 2 ) ) ) ) count ++ ; } } cout << count << endl ; } int main ( ) { sieveoferanthones ( ) ; long long int n = 9 ; numberOfWays ( n ) ; return 0 ; } |
Program to convert Degree to Radian | C ++ program to convert degree to radian ; Function for conversion ; Driver code | #include <iostream> NEW_LINE #include <math.h> NEW_LINE using namespace std ; double Convert ( double degree ) { double pi = 3.14159265359 ; return ( degree * ( pi / 180 ) ) ; } int main ( ) { double degree = 30 ; double radian = Convert ( degree ) ; cout << radian ; return 0 ; } |
Program to convert a Binary Number to Hexa | C ++ code to convert Binary to its HexaDecimal number ( base 16 ) . ; Function to convert Binary to HexaDecimal ; Iterating through the bits backwards ; Computing the HexaDecimal Number formed so far and storing it in a vector . ; Reinitializing all variables for next group . ; Printing the Hexadecimal number formed so far . ; Driver Code ; Function Call | #include <bits/stdc++.h> NEW_LINE using namespace std ; void bToHexaDecimal ( string s ) { int len = s . length ( ) , check = 0 ; int num = 0 , sum = 0 , mul = 1 ; vector < char > ans ; for ( int i = len - 1 ; i >= 0 ; i -- ) { sum += ( s [ i ] - '0' ) * mul ; mul *= 2 ; check ++ ; if ( check == 4 i == 0 ) { if ( sum <= 9 ) ans . push_back ( sum + '0' ) ; else ans . push_back ( sum + 55 ) ; check = 0 ; sum = 0 ; mul = 1 ; } } len = ans . size ( ) ; for ( int i = len - 1 ; i >= 0 ; i -- ) cout << ans [ i ] ; } int main ( ) { string s = "100000101111" ; bToHexaDecimal ( s ) ; return 0 ; } |
Find the sum of the first N Dodecagonal Numbers | C ++ program to find the sum of the first N dodecagonal numbers ; Function to find the N - th dodecagonal number ; Formula to calculate N - th dodecagonal number ; Function to find the sum of the first N dodecagonal numbers ; Variable to get the sum ; Iterating through the first N numbers ; Compute the sum ; Driver Code ; Display first Nth centered_decagonal number | #include <bits/stdc++.h> NEW_LINE using namespace std ; int Dodecagonal_num ( int n ) { return ( 5 * n * n - 4 * n ) ; } int sum_Dodecagonal_num ( int n ) { int summ = 0 ; for ( int i = 1 ; i < n + 1 ; i ++ ) { summ += Dodecagonal_num ( i ) ; } return summ ; } int main ( ) { int n = 5 ; cout << ( sum_Dodecagonal_num ( n ) ) ; return 0 ; } |
Program to check if N is a Myriagon Number | C ++ program for the above approach ; Function to check if N is a Myriagon Number ; Condition to check if the number is a Myriagon number ; Driver Code ; Given Number ; Function call | #include <bits/stdc++.h> NEW_LINE using namespace std ; bool isMyriagon ( int N ) { float n = ( 9996 + sqrt ( 79984 * N + 99920016 ) ) / 19996 ; return ( n - ( int ) n ) == 0 ; } int main ( ) { int N = 10000 ; if ( isMyriagon ( N ) ) { cout << " Yes " ; } else { cout << " No " ; } return 0 ; } |
Program to check if N is a Heptagonal Number | C ++ program for the above approach ; Function to check if N is a Heptagonal number ; Condition to check if the number is a heptagonal number ; Driver Code ; Given Number ; Function call | #include <bits/stdc++.h> NEW_LINE using namespace std ; bool isheptagonal ( int N ) { float n = ( 3 + sqrt ( 40 * N + 9 ) ) / 10 ; return ( n - ( int ) n ) == 0 ; } int main ( ) { int N = 7 ; if ( isheptagonal ( N ) ) { cout << " Yes " ; } else { cout << " No " ; } return 0 ; } |
Program to check if N is a Enneadecagonal Number | C ++ program for the above approach ; Function to check if number N is a enneadecagonal number ; Condition to check if N is a enneadecagonal number ; Driver Code ; Given Number ; Function call | #include <bits/stdc++.h> NEW_LINE using namespace std ; bool isenneadecagonal ( int N ) { float n = ( 15 + sqrt ( 136 * N + 225 ) ) / 34 ; return ( n - ( int ) n ) == 0 ; } int main ( ) { int N = 19 ; if ( isenneadecagonal ( N ) ) { cout << " Yes " ; } else { cout << " No " ; } return 0 ; } |
Program to check if N is a Centered Tridecagonal Number | C ++ program for the above approach ; Function to check if the number N is a Centered tridecagonal number ; Condition to check if the N is a Centered tridecagonal number ; Driver Code ; Given Number ; Function call | #include <bits/stdc++.h> NEW_LINE using namespace std ; bool isCenteredtridecagonal ( int N ) { float n = ( 13 + sqrt ( 104 * N + 65 ) ) / 26 ; return ( n - ( int ) n ) == 0 ; } int main ( ) { int N = 14 ; if ( isCenteredtridecagonal ( N ) ) { cout << " Yes " ; } else { cout << " No " ; } return 0 ; } |
Orbit counting theorem or Burnside 's Lemma | C ++ program for implementing the Orbit counting theorem or Burnside 's Lemma ; Function to find result using Orbit counting theorem or Burnside 's Lemma ; According to Burnside 's Lemma calculate distinct ways for each rotation ; Find GCD ; Divide By N ; Print the distinct ways ; Driver Code ; N stones and M colors ; Function call | #include <bits/stdc++.h> NEW_LINE using namespace std ; void countDistinctWays ( int N , int M ) { int ans = 0 ; for ( int i = 0 ; i < N ; i ++ ) { int K = __gcd ( i , N ) ; ans += pow ( M , K ) ; } ans /= N ; cout << ans << endl ; } int main ( ) { int N = 4 , M = 3 ; countDistinctWays ( N , M ) ; return 0 ; } |
Find the Nth natural number which is not divisible by A | C ++ code to Find the Nth number which is not divisible by A from the series ; Find the quotient and the remainder when k is divided by n - 1 ; If the remainder is not 0 multiply n by q and subtract 1 if remainder is 0 then multiply n by q and add the remainder ; Print the answer ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; void findNum ( int n , int k ) { int q = k / ( n - 1 ) ; int r = k % ( n - 1 ) ; int a ; if ( r != 0 ) a = ( n * q ) + r ; else a = ( n * q ) - 1 ; cout << a ; } int main ( ) { int A = 4 , N = 6 ; findNum ( A , N ) ; return 0 ; } |
Count the nodes in the given Tree whose weight is a Perfect Number | C ++ implementation to Count the nodes in the given tree whose weight is a Perfect Number ; Function that returns true if n is perfect ; Variable to store sum of divisors ; Find all divisors and add them ; Check if sum of divisors is equal to n , then n is a perfect number ; Function to perform dfs ; If weight of the current node is a perfect number ; Driver code ; Weights of the node ; Edges of the tree | #include <bits/stdc++.h> NEW_LINE using namespace std ; int ans = 0 ; vector < int > graph [ 100 ] ; vector < int > weight ( 100 ) ; bool isPerfect ( long long int n ) { long long int sum = 1 ; for ( long long 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 true ; return false ; } void dfs ( int node , int parent ) { if ( isPerfect ( weight [ node ] ) ) ans += 1 ; for ( int to : graph [ node ] ) { if ( to == parent ) continue ; dfs ( to , node ) ; } } int main ( ) { weight [ 1 ] = 5 ; weight [ 2 ] = 10 ; weight [ 3 ] = 11 ; weight [ 4 ] = 8 ; weight [ 5 ] = 6 ; graph [ 1 ] . push_back ( 2 ) ; graph [ 2 ] . push_back ( 3 ) ; graph [ 2 ] . push_back ( 4 ) ; graph [ 1 ] . push_back ( 5 ) ; dfs ( 1 , 1 ) ; cout << ans ; return 0 ; } |
Minimum cost to merge numbers from 1 to N | C ++ program to find the Minimum cost to merge numbers from 1 to N . ; Function returns the minimum cost ; Min Heap representation ; Add all elements to heap ; First minimum ; Second minimum ; Multiply them ; Add to the cost ; Push the product into the heap again ; Return the optimal cost ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int GetMinCost ( int N ) { priority_queue < int , vector < int > , greater < int > > pq ; for ( int i = 1 ; i <= N ; i ++ ) { pq . push ( i ) ; } int cost = 0 ; while ( pq . size ( ) > 1 ) { int mini = pq . top ( ) ; pq . pop ( ) ; int secondmini = pq . top ( ) ; pq . pop ( ) ; int current = mini * secondmini ; cost += current ; pq . push ( current ) ; } return cost ; } int main ( ) { int N = 5 ; cout << GetMinCost ( N ) ; } |
Permutation of first N positive integers such that prime numbers are at prime indices | Set 2 | C ++ program to count permutations from 1 to N such that prime numbers occur at prime indices ; ; Computing count of prime numbers using sieve ; Computing permutations for primes ; Computing permutations for non - primes ; Driver program | #include <bits/stdc++.h> NEW_LINE using namespace std ; static const int MOD = 1e9 + 7 ; int numPrimeArrangements ( int n ) { vector < bool > prime ( n + 1 , true ) ; prime [ 0 ] = false ; prime [ 1 ] = false ; for ( int i = 2 ; i <= sqrt ( n ) ; i ++ ) { if ( prime [ i ] ) for ( int factor = 2 ; factor * i <= n ; factor ++ ) prime [ factor * i ] = false ; } int primeIndices = 0 ; for ( int i = 1 ; i <= n ; i ++ ) if ( prime [ i ] ) primeIndices ++ ; int mod = 1e9 + 7 , res = 1 ; for ( int i = 1 ; i <= primeIndices ; i ++ ) res = ( 1LL * res * i ) % mod ; for ( int i = 1 ; i <= ( n - primeIndices ) ; i ++ ) res = ( 1LL * res * i ) % mod ; return res ; } int main ( ) { int N = 5 ; cout << numPrimeArrangements ( N ) ; return 0 ; } |
Probability of getting K heads in N coin tosses | C ++ program to find probability of getting K heads in N coin tosses ; function to calculate factorial ; apply the formula ; Driver function ; call count_heads with n and r | #include <bits/stdc++.h> NEW_LINE using namespace std ; int fact ( int n ) { int res = 1 ; for ( int i = 2 ; i <= n ; i ++ ) res = res * i ; return res ; } double count_heads ( int n , int r ) { double output ; output = fact ( n ) / ( fact ( r ) * fact ( n - r ) ) ; output = output / ( pow ( 2 , n ) ) ; return output ; } int main ( ) { int n = 4 , r = 3 ; cout << count_heads ( n , r ) ; return 0 ; } |
Largest component size in a graph formed by connecting non | ; mark this node as visited ; apply dfs and add nodes belonging to this component ; create graph and store in adjacency list form ; iterate over all pair of nodes ; if not co - prime ; build undirected graph ; visited array for dfs ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int dfs ( int u , vector < int > * adj , int vis [ ] ) { vis [ u ] = 1 ; int componentSize = 1 ; for ( auto it : adj [ u ] ) { if ( ! vis [ it ] ) { componentSize += dfs ( it , adj , vis ) ; } } return componentSize ; } int maximumComponentSize ( int a [ ] , int n ) { vector < int > adj [ n ] ; for ( int i = 0 ; i < n ; i ++ ) { for ( int j = i + 1 ; j < n ; j ++ ) { if ( __gcd ( a [ i ] , a [ j ] ) > 1 ) adj [ i ] . push_back ( j ) ; adj [ j ] . push_back ( i ) ; } } int answer = 0 ; int vis [ n ] ; for ( int k = 0 ; k < n ; k ++ ) { vis [ k ] = 0 ; } for ( int i = 0 ; i < n ; i ++ ) { if ( ! vis [ i ] ) { answer = max ( answer , dfs ( i , adj , vis ) ) ; } } return answer ; } int main ( ) { int n = 8 ; int A [ ] = { 2 , 3 , 6 , 7 , 4 , 12 , 21 , 39 } J2 : J6 ; cout << maximumComponentSize ( A , n ) ; return 0 ; } |
Largest component size in a graph formed by connecting non | ; smallest prime factor ; Sieve of Eratosthenes ; is spf [ i ] = 0 , then it 's prime ; smallest prime factor of all multiples is i ; Prime factorise n , and store prime factors in set s ; for implementing DSU ; root of component of node i ; finding root as well as applying path compression ; merging two components ; find roots of both components ; if already belonging to the same compenent ; Union by rank , the rank in this case is sizeContainer of the component . Smaller sizeContainer will be merged into larger , so the larger 's root will be final root ; Function to find the maximum sized container ; intitalise the parents , and component sizeContainer ; intitally all component sizeContainers are 1 ans each node it parent of itself ; store prime factors of a [ i ] in s ; if this prime is seen as a factor for the first time ; if not then merge with that component in which this prime was previously seen ; maximum of sizeContainer of all components ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int spf [ 100005 ] ; void sieve ( ) { for ( int i = 2 ; i < 100005 ; i ++ ) { if ( spf [ i ] == 0 ) { spf [ i ] = i ; for ( int j = 2 * i ; j < 100005 ; j += i ) { if ( spf [ j ] == 0 ) spf [ j ] = i ; } } } } void factorize ( int n , set < int > & s ) { while ( n > 1 ) { int z = spf [ n ] ; s . insert ( z ) ; while ( n % z == 0 ) n /= z ; } } int id [ 100005 ] ; int par [ 100005 ] ; int sizeContainer [ 100005 ] ; int root ( int i ) { if ( par [ i ] == i ) return i ; else return par [ i ] = root ( par [ i ] ) ; } void merge ( int a , int b ) { int p = root ( a ) ; int q = root ( b ) ; if ( p == q ) return ; if ( sizeContainer [ p ] > sizeContainer [ q ] ) swap ( p , q ) ; par [ p ] = q ; sizeContainer [ q ] += sizeContainer [ p ] ; } int maximumComponentsizeContainer ( int a [ ] , int n ) { for ( int i = 0 ; i < 100005 ; i ++ ) { par [ i ] = i ; sizeContainer [ i ] = 1 ; } sieve ( ) ; for ( int i = 0 ; i < n ; i ++ ) { set < int > s ; factorize ( a [ i ] , s ) ; for ( auto it : s ) { if ( id [ it ] == 0 ) id [ it ] = i + 1 ; else merge ( i + 1 , id [ it ] ) ; } } int answer = 0 ; for ( int i = 0 ; i < n ; i ++ ) answer = max ( answer , sizeContainer [ i ] ) ; return answer ; } int main ( ) { int n = 8 ; int A [ ] = { 2 , 3 , 6 , 7 , 4 , 12 , 21 , 39 } ; cout << maximumComponentsizeContainer ( A , n ) ; return 0 ; } |
Count of nodes in a Binary Tree whose child is its prime factors | C ++ program for Counting nodes whose immediate children are its factors ; To store all prime numbers ; Create a boolean array " prime [ 0 . . N ] " and initialize all its entries as true . A value in prime [ i ] will finally be false if i is Not a prime , else true . ; If prime [ p ] is not changed , then it is a prime ; Update all multiples of p greater than or equal to the square of it numbers which are multiples of p and are less than p ^ 2 are already marked . ; A Tree node ; Utility function to create a new node ; Function to check if immediate children of a node are its factors or not ; Function to get the count of full Nodes in a binary tree ; If tree is empty ; Initialize count of full nodes having children as their factors ; If only right child exist ; If only left child exist ; Both left and right child exist ; Check for left child ; Check for right child ; Driver Code ; Create Binary Tree as shown ; To save all prime numbers ; Print Count of all nodes having children as their factors | #include <bits/stdc++.h> NEW_LINE using namespace std ; int N = 1000000 ; vector < int > prime ; void SieveOfEratosthenes ( ) { bool check [ N + 1 ] ; memset ( check , true , sizeof ( check ) ) ; for ( int p = 2 ; p * p <= N ; p ++ ) { if ( check [ p ] == true ) { prime . push_back ( p ) ; for ( int i = p * p ; i <= N ; i += p ) check [ i ] = false ; } } } struct Node { int key ; struct Node * left , * right ; } ; Node * newNode ( int key ) { Node * temp = new Node ; temp -> key = key ; temp -> left = temp -> right = NULL ; return ( temp ) ; } bool IsChilrenPrimeFactor ( struct Node * parent , struct Node * a ) { if ( prime [ a -> key ] && ( parent -> key % a -> key == 0 ) ) return true ; else return false ; } unsigned int GetCount ( struct Node * node ) { if ( ! node ) return 0 ; queue < Node * > q ; int count = 0 ; q . push ( node ) ; while ( ! q . empty ( ) ) { struct Node * temp = q . front ( ) ; q . pop ( ) ; if ( temp -> left == NULL && temp -> right != NULL ) { if ( IsChilrenPrimeFactor ( temp , temp -> right ) ) count ++ ; } else { if ( temp -> right == NULL && temp -> left != NULL ) { if ( IsChilrenPrimeFactor ( temp , temp -> left ) ) count ++ ; } else { if ( temp -> left != NULL && temp -> right != NULL ) { if ( IsChilrenPrimeFactor ( temp , temp -> right ) && IsChilrenPrimeFactor ( temp , temp -> left ) ) count ++ ; } } } if ( temp -> left != NULL ) q . push ( temp -> left ) ; if ( temp -> right != NULL ) q . push ( temp -> right ) ; } return count ; } int main ( ) { Node * root = newNode ( 10 ) ; root -> left = newNode ( 2 ) ; root -> right = newNode ( 5 ) ; root -> right -> left = newNode ( 18 ) ; root -> right -> right = newNode ( 12 ) ; root -> right -> left -> left = newNode ( 2 ) ; root -> right -> left -> right = newNode ( 3 ) ; root -> right -> right -> left = newNode ( 3 ) ; root -> right -> right -> right = newNode ( 14 ) ; root -> right -> right -> right -> left = newNode ( 7 ) ; SieveOfEratosthenes ( ) ; cout << GetCount ( root ) << endl ; return 0 ; } |
Check if original Array is retained after performing XOR with M exactly K times | C ++ implementation for the above mentioned problem ; Function to check if original Array can be retained by performing XOR with M exactly K times ; Check if O is present or not ; If K is odd and 0 is not present then the answer will always be No . ; Else it will be Yes ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; string check ( int Arr [ ] , int n , int M , int K ) { int flag = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( Arr [ i ] == 0 ) flag = 1 ; } if ( K % 2 != 0 && flag == 0 ) return " No " ; else return " Yes " ; } int main ( ) { int Arr [ ] = { 1 , 1 , 2 , 4 , 7 , 8 } ; int M = 5 ; int K = 6 ; int n = sizeof ( Arr ) / sizeof ( Arr [ 0 ] ) ; cout << check ( Arr , n , M , K ) ; return 0 ; } |
Dixon 's Factorization Method with implementation | C ++ implementation of Dixon factorization algo ; Function to find the factors of a number using the Dixon Factorization Algorithm ; Factor base for the given number ; Starting from the ceil of the root of the given number N ; Storing the related squares ; For every number from the square root Till N ; Finding the related squares ; If the two numbers are the related squares , then append them to the array ; For every pair in the array , compute the GCD such that ; If we find a factor other than 1 , then appending it to the final factor array ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; #include <vector> NEW_LINE void factor ( int n ) { int base [ 4 ] = { 2 , 3 , 5 , 7 } ; int start = int ( sqrt ( n ) ) ; vector < vector < int > > pairs ; int len = sizeof ( base ) / sizeof ( base [ 0 ] ) ; for ( int i = start ; i < n ; i ++ ) { vector < int > v ; for ( int j = 0 ; j < len ; j ++ ) { int lhs = ( ( int ) pow ( i , 2 ) ) % n ; int rhs = ( ( int ) pow ( base [ j ] , 2 ) ) % n ; if ( lhs == rhs ) { v . push_back ( i ) ; v . push_back ( base [ j ] ) ; pairs . push_back ( v ) ; } } } vector < int > newvec ; len = pairs . size ( ) ; for ( int i = 0 ; i < len ; i ++ ) { int factor = __gcd ( pairs [ i ] [ 0 ] - pairs [ i ] [ 1 ] , n ) ; if ( factor != 1 ) newvec . push_back ( factor ) ; } set < int > s ; for ( int i = 0 ; i < newvec . size ( ) ; i ++ ) s . insert ( newvec [ i ] ) ; for ( auto i = s . begin ( ) ; i != s . end ( ) ; i ++ ) cout << ( * i ) << " β " ; } int main ( ) { factor ( 23449 ) ; } |
Longest sub | C ++ program to find longest subarray of prime numbers ; To store the prime numbers ; Function that find prime numbers till limit ; Find primes using Sieve of Eratosthenes ; Function that finds all prime numbers in given range using Segmented Sieve ; Find the limit ; To store the prime numbers ; Comput all primes less than or equals to sqrt ( high ) using Simple Sieve ; Count the elements in the range [ low , high ] ; Declaring boolean for the range [ low , high ] ; Traverse the prime numbers till limit ; Find the minimum number in [ low . . high ] that is a multiple of prime [ i ] ; Mark the multiples of prime [ i ] in [ low , high ] as true ; Element which are not marked in range are Prime ; Function that finds longest subarray of prime numbers ; If element is Non - prime then updated current_max to 0 ; If element is prime , then update current_max and max_so_far ; Return the count of longest subarray ; Driver Code ; Find minimum and maximum element ; Find prime in the range [ min_el , max_el ] ; Function call | #include <bits/stdc++.h> NEW_LINE using namespace std ; unordered_set < int > allPrimes ; void simpleSieve ( int limit , vector < int > & prime ) { bool mark [ limit + 1 ] ; memset ( mark , false , sizeof ( mark ) ) ; for ( int i = 2 ; i <= limit ; ++ i ) { if ( mark [ i ] == false ) { prime . push_back ( i ) ; for ( int j = i ; j <= limit ; j += i ) { mark [ j ] = true ; } } } } void primesInRange ( int low , int high ) { int limit = floor ( sqrt ( high ) ) + 1 ; vector < int > prime ; simpleSieve ( limit , prime ) ; int n = high - low + 1 ; bool mark [ n + 1 ] ; memset ( mark , false , sizeof ( mark ) ) ; for ( int i = 0 ; i < prime . size ( ) ; i ++ ) { int loLim = floor ( low / prime [ i ] ) ; loLim *= prime [ i ] ; if ( loLim < low ) { loLim += prime [ i ] ; } if ( loLim == prime [ i ] ) { loLim += prime [ i ] ; } for ( int j = loLim ; j <= high ; j += prime [ i ] ) mark [ j - low ] = true ; } for ( int i = low ; i <= high ; i ++ ) { if ( ! mark [ i - low ] ) { allPrimes . insert ( i ) ; } } } int maxPrimeSubarray ( int arr [ ] , int n ) { int current_max = 0 ; int max_so_far = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( ! allPrimes . count ( arr [ i ] ) ) current_max = 0 ; else { current_max ++ ; max_so_far = max ( current_max , max_so_far ) ; } } return max_so_far ; } int main ( ) { int arr [ ] = { 1 , 2 , 4 , 3 , 29 , 11 , 7 , 8 , 9 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; int max_el = * max_element ( arr , arr + n ) ; int min_el = * min_element ( arr , arr + n ) ; primesInRange ( min_el , max_el ) ; cout << maxPrimeSubarray ( arr , n ) ; return 0 ; } |
Sum of all armstrong numbers lying in the range [ L , R ] for Q queries | C ++ program to find the sum of all armstrong numbers in the given range ; pref [ ] array to precompute the sum of all armstrong number ; Function that return number num if num is armstrong else return 0 ; Function to precompute the sum of all armstrong numbers upto 100000 ; checkarmstrong ( ) return the number i if i is armstrong else return 0 ; Function to print the sum for each query ; Function to prsum of all armstrong numbers between [ L , R ] ; Function that pre computes the sum of all armstrong numbers ; Iterate over all Queries to print the sum ; Driver code ; Queries ; Function that print the the sum of all armstrong number in Range [ L , R ] | #include <bits/stdc++.h> NEW_LINE using namespace std ; int pref [ 100001 ] = { 0 } ; static int checkArmstrong ( int x ) { int n = to_string ( x ) . size ( ) ; int sum1 = 0 ; int temp = x ; while ( temp > 0 ) { int digit = temp % 10 ; sum1 += pow ( digit , n ) ; temp /= 10 ; } if ( sum1 == x ) return x ; return 0 ; } void preCompute ( ) { for ( int i = 1 ; i < 100001 ; i ++ ) { pref [ i ] = pref [ i - 1 ] + checkArmstrong ( i ) ; } } void printSum ( int L , int R ) { cout << ( pref [ R ] - pref [ L - 1 ] ) << endl ; } void printSumarmstrong ( int arr [ 2 ] [ 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 ] [ 2 ] = { { 1 , 13 } , { 121 , 211 } } ; printSumarmstrong ( arr , Q ) ; return 0 ; } |
Count of pairs in an array whose product is a perfect square | C ++ program to calculate the number of pairs with product is perfect square ; Prime [ ] array to calculate Prime Number ; Array k [ ] to store the value of k for each element in arr [ ] ; For value of k , Sieve function is implemented ; Initialize k [ i ] to i ; Prime Sieve ; If i is prime then remove all factors of prime from it ; Update that j is not prime ; Remove all square divisors i . e . if k [ j ] is divisible by i * i then divide it by i * i ; Function that return total count of pairs with perfect square product ; Map used to store the frequency of k ; Store the frequency of k ; The total number of pairs is the summation of ( fi * ( fi - 1 ) ) / 2 ; Driver code ; Size of arr [ ] ; To pre - compute the value of k ; Function that return total count of pairs with perfect square product | #include <bits/stdc++.h> NEW_LINE using namespace std ; int prime [ 100001 ] = { 0 } ; int k [ 100001 ] = { 0 } ; void Sieve ( ) { for ( int i = 1 ; i < 100001 ; i ++ ) k [ i ] = i ; for ( int i = 2 ; i < 100001 ; i ++ ) { if ( prime [ i ] == 0 ) for ( int j = i ; j < 100001 ; j += i ) { prime [ j ] = 1 ; while ( k [ j ] % ( i * i ) == 0 ) k [ j ] /= ( i * i ) ; } } } int countPairs ( int arr [ ] , int n ) { unordered_map < int , int > freq ; for ( int i = 0 ; i < n ; i ++ ) { freq [ k [ arr [ i ] ] ] ++ ; } int sum = 0 ; for ( auto i : freq ) { sum += ( ( i . second - 1 ) * i . second ) / 2 ; } return sum ; } int main ( ) { int arr [ ] = { 1 , 2 , 4 , 8 , 5 , 6 } ; int n = sizeof ( arr ) / sizeof ( int ) ; Sieve ( ) ; cout << countPairs ( arr , n ) << endl ; return 0 ; } |
Sum of all Perfect Cubes lying in the range [ L , R ] for Q queries | C ++ program to find the sum of all perfect cubes in the given range ; Array to precompute the sum of cubes from 1 to 100010 so that for every query , the answer can be returned in O ( 1 ) . ; Function to check if a number is a perfect Cube or not ; Find floating point value of cube root of x . ; If cube root of x is cr return the x , else 0 ; Function to precompute the perfect Cubes upto 100000. ; Function to print the sum for each query ; Driver code ; To calculate the precompute function ; Calling the printSum function for every query | #include <bits/stdc++.h> NEW_LINE #define ll int NEW_LINE using namespace std ; long long pref [ 100010 ] ; int isPerfectCube ( long long int x ) { long double cr = round ( cbrt ( x ) ) ; return ( cr * cr * cr == x ) ? x : 0 ; } void compute ( ) { for ( int i = 1 ; i <= 100000 ; ++ i ) { pref [ i ] = pref [ i - 1 ] + isPerfectCube ( i ) ; } } void printSum ( int L , int R ) { int sum = pref [ R ] - pref [ L - 1 ] ; cout << sum << " β " ; } int main ( ) { compute ( ) ; int Q = 4 ; int arr [ ] [ 2 ] = { { 1 , 10 } , { 1 , 100 } , { 2 , 25 } , { 4 , 50 } } ; for ( int i = 0 ; i < Q ; i ++ ) { printSum ( arr [ i ] [ 0 ] , arr [ i ] [ 1 ] ) ; } return 0 ; } |
Total number of Subsets of size at most K | C ++ code to find total number of Subsets of size at most K ; Function to compute the value of Binomial Coefficient C ( n , k ) ; Calculate value of Binomial Coefficient in bottom up manner ; Base Cases ; Calculate value using previously stored values ; Function to calculate sum of nCj from j = 1 to k ; Calling the nCr function for each value of j ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int binomialCoeff ( int n , int k ) { int C [ n + 1 ] [ k + 1 ] ; int i , j ; for ( i = 0 ; i <= n ; i ++ ) { for ( j = 0 ; j <= min ( i , k ) ; j ++ ) { if ( j == 0 j == i ) C [ i ] [ j ] = 1 ; else C [ i ] [ j ] = C [ i - 1 ] [ j - 1 ] + C [ i - 1 ] [ j ] ; } } return C [ n ] [ k ] ; } int count ( int n , int k ) { int sum = 0 ; for ( int j = 1 ; j <= k ; j ++ ) { sum = sum + binomialCoeff ( n , j ) ; } return sum ; } int main ( ) { int n = 3 , k = 2 ; cout << count ( n , k ) ; n = 5 , k = 2 ; cout << count ( n , k ) ; return 0 ; } |
Tree Isomorphism Problem | A C ++ program to check if two given trees are isomorphic ; A binary tree node has data , pointer to left and right children ; Given a binary tree , print its nodes in reverse level order ; Both roots are NULL , trees isomorphic by definition ; Exactly one of the n1 and n2 is NULL , trees not isomorphic ; There are two possible cases for n1 and n2 to be isomorphic Case 1 : The subtrees rooted at these nodes have NOT been " Flipped " . Both of these subtrees have to be isomorphic , hence the && Case 2 : The subtrees rooted at these nodes have been " Flipped " ; Helper function that allocates a new node with the given data and NULL left and right pointers . ; Driver program to test above functions ; Let us create trees shown in above diagram | #include <iostream> NEW_LINE using namespace std ; struct node { int data ; struct node * left ; struct node * right ; } ; bool isIsomorphic ( node * n1 , node * n2 ) { if ( n1 == NULL && n2 == NULL ) return true ; if ( n1 == NULL n2 == NULL ) return false ; if ( n1 -> data != n2 -> data ) return false ; return ( isIsomorphic ( n1 -> left , n2 -> left ) && isIsomorphic ( n1 -> right , n2 -> right ) ) || ( isIsomorphic ( n1 -> left , n2 -> right ) && isIsomorphic ( n1 -> right , n2 -> left ) ) ; } node * newNode ( int data ) { node * temp = new node ; temp -> data = data ; temp -> left = NULL ; temp -> right = NULL ; return ( temp ) ; } int main ( ) { struct node * n1 = newNode ( 1 ) ; n1 -> left = newNode ( 2 ) ; n1 -> right = newNode ( 3 ) ; n1 -> left -> left = newNode ( 4 ) ; n1 -> left -> right = newNode ( 5 ) ; n1 -> right -> left = newNode ( 6 ) ; n1 -> left -> right -> left = newNode ( 7 ) ; n1 -> left -> right -> right = newNode ( 8 ) ; struct node * n2 = newNode ( 1 ) ; n2 -> left = newNode ( 3 ) ; n2 -> right = newNode ( 2 ) ; n2 -> right -> left = newNode ( 4 ) ; n2 -> right -> right = newNode ( 5 ) ; n2 -> left -> right = newNode ( 6 ) ; n2 -> right -> right -> left = newNode ( 8 ) ; n2 -> right -> right -> right = newNode ( 7 ) ; if ( isIsomorphic ( n1 , n2 ) == true ) cout << " Yes " ; else cout << " No " ; return 0 ; } |
Find smallest number with given number of digits and sum of digits under given constraints | C ++ implementation of the approach ; Function to find the number having sum of digits as s and d number of digits such that the difference between the maximum and the minimum digit the minimum possible ; To store the final number ; To store the value that is evenly distributed among all the digits ; To store the remaining sum that still remains to be distributed among d digits ; rem stores the value that still remains to be distributed To keep the difference of digits minimum last rem digits are incremented by 1 ; In the last rem digits one is added to the value obtained by equal distribution ; Driver function | #include <bits/stdc++.h> NEW_LINE using namespace std ; string findNumber ( int s , int d ) { string num = " " ; int val = s / d ; int rem = s % d ; int i ; for ( i = 1 ; i <= d - rem ; i ++ ) { num = num + to_string ( val ) ; } if ( rem ) { val ++ ; for ( i = d - rem + 1 ; i <= d ; i ++ ) { num = num + to_string ( val ) ; } } return num ; } int main ( ) { int s = 25 , d = 4 ; cout << findNumber ( s , d ) ; return 0 ; } |
Find Kth smallest value for b such that a + b = a | b | C ++ program to find k 'th smallest value for b such that a + b = a | b ; Function to find the kth smallest value for b ; res will store final answer ; skip when j ' th β position β β has β 1 β in β binary β representation β β as β in β res , β j ' th position will be 0. ; j 'th bit is set ; i 'th bit is set ; proceed to next bit ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; #define ll long long NEW_LINE ll kthSmallest ( ll a , ll k ) { ll res = 0 ; ll j = 0 ; for ( ll i = 0 ; i < 32 ; i ++ ) { while ( j < 32 && ( a & ( 1 << j ) ) ) j ++ ; if ( k & ( 1 << i ) ) res |= ( 1LL << j ) ; j ++ ; } return res ; } int main ( ) { ll a = 10 , k = 3 ; cout << kthSmallest ( a , k ) << " STRNEWLINE " ; return 0 ; } |
Find the sum of power of bit count raised to the power B | C ++ program for the above approach ; Function to calculate a ^ b mod m using fast - exponentiation method ; Function to calculate sum ; Itereate for all values of array A ; Calling fast - exponentiation and appending ans to sum ; Driver code . | #include <bits/stdc++.h> NEW_LINE using namespace std ; int fastmod ( int base , int exp , int mod ) { if ( exp == 0 ) return 1 ; else if ( exp % 2 == 0 ) { int ans = fastmod ( base , exp / 2 , mod ) ; return ( ans % mod * ans % mod ) % mod ; } else return ( fastmod ( base , exp - 1 , mod ) % mod * base % mod ) % mod ; } int findPowerSum ( int n , int ar [ ] ) { const int mod = 1e9 + 7 ; int sum = 0 ; for ( int i = 0 ; i < n ; i ++ ) { int base = __builtin_popcount ( ar [ i ] ) ; int exp = ar [ i ] ; sum += fastmod ( base , exp , mod ) ; sum %= mod ; } return sum ; } int main ( ) { int n = 3 ; int ar [ ] = { 1 , 2 , 3 } ; cout << findPowerSum ( n , ar ) ; return 0 ; } |
Count the total number of triangles after Nth operation | ; function to return the total no . of Triangles ; For every subtriangle formed there are possibilities of generating ( curr * 3 ) + 2 ; Changing the curr value to Tri_count ; driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int CountTriangles ( int n ) { int curr = 1 ; int Tri_count = 0 ; for ( int i = 1 ; i <= n ; i ++ ) { Tri_count = ( curr * 3 ) + 2 ; curr = Tri_count ; } return Tri_count ; } int main ( ) { int n = 10 ; cout << CountTriangles ( n ) ; return 0 ; } |
In how many ways the ball will come back to the first boy after N turns | Function to return the number of sequences that get back to Bob ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int numSeq ( int n ) { return ( pow ( 3 , n ) + 3 * pow ( -1 , n ) ) / 4 ; } int main ( ) { int N = 10 ; printf ( " % d " , numSeq ( N ) ) ; return 0 ; } |
Count subarrays such that remainder after dividing sum of elements by K gives count of elements | C ++ implementation of the approach ; Function to return the number of subarrays of the given array such that the remainder when dividing the sum of its elements by K is equal to the number of its elements ; To store prefix sum ; We are dealing with zero indexed array ; Taking modulus value ; Prefix sum ; To store the required answer , the left index and the right index ; To store si - i value ; Include sum ; Increment the right index ; If subarray has at least k elements ; Return the required answer ; Driver code ; Function call | #include <bits/stdc++.h> NEW_LINE using namespace std ; int sub_arrays ( int a [ ] , int n , int k ) { int sum [ n + 2 ] = { 0 } ; for ( int i = 0 ; i < n ; i ++ ) { a [ i ] -- ; a [ i ] %= k ; sum [ i + 1 ] += sum [ i ] + a [ i ] ; sum [ i + 1 ] %= k ; } int ans = 0 , l = 0 , r = 0 ; map < int , int > mp ; for ( int i = 0 ; i < n + 1 ; i ++ ) { ans += mp [ sum [ i ] ] ; mp [ sum [ i ] ] ++ ; r ++ ; if ( r - l >= k ) { mp [ sum [ l ] ] -- ; l ++ ; } } return ans ; } int main ( ) { int a [ ] = { 1 , 4 , 2 , 3 , 5 } ; int n = sizeof ( a ) / sizeof ( a [ 0 ] ) ; int k = 4 ; cout << sub_arrays ( a , n , k ) ; return 0 ; } |
Sum of all the prime numbers with the maximum position of set bit Γ’ β°Β€ D | C ++ ; Function for Sieve of Eratosthenes ; Function to return the sum of the required prime numbers ; Maximum number of the required range ; Sieve of Eratosthenes ; To store the required sum ; If current element is prime ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; void sieve ( bool prime [ ] , int n ) { prime [ 0 ] = false ; prime [ 1 ] = false ; for ( int p = 2 ; p * p <= n ; p ++ ) { if ( prime [ p ] == true ) { for ( int i = p * p ; i <= n ; i += p ) prime [ i ] = false ; } } } int sumPrime ( int d ) { int maxVal = pow ( 2 , d ) - 1 ; bool prime [ maxVal + 1 ] ; memset ( prime , true , sizeof ( prime ) ) ; sieve ( prime , maxVal ) ; int sum = 0 ; for ( int i = 2 ; i <= maxVal ; i ++ ) { if ( prime [ i ] ) { sum += i ; } } return sum ; } int main ( ) { int d = 8 ; cout << sumPrime ( d ) ; return 0 ; } |
Check whether the exchange is possible or not | C ++ implementation of the approach ; Function that returns true if the exchange is possible ; Find the GCD of the array elements ; If the exchange is possible ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; bool isPossible ( int arr [ ] , int n , int p ) { int gcd = 0 ; for ( int i = 0 ; i < n ; i ++ ) gcd = __gcd ( gcd , arr [ i ] ) ; if ( p % gcd == 0 ) return true ; return false ; } int main ( ) { int arr [ ] = { 6 , 9 } ; int n = sizeof ( arr ) / sizeof ( int ) ; int p = 3 ; if ( isPossible ( arr , n , p ) ) cout << " Yes " ; else cout << " No " ; return 0 ; } |
Choose two elements from the given array such that their sum is not present in any of the arrays | C ++ implementation of the approach ; Function to find the numbers from the given arrays such that their sum is not present in any of the given array ; Find the maximum element from both the arrays ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; void findNum ( int a [ ] , int n , int b [ ] , int m ) { int x = * max_element ( a , a + n ) ; int y = * max_element ( b , b + m ) ; cout << x << " β " << y ; } int main ( ) { int a [ ] = { 3 , 2 , 2 } ; int n = sizeof ( a ) / sizeof ( int ) ; int b [ ] = { 1 , 5 , 7 , 7 , 9 } ; int m = sizeof ( b ) / sizeof ( int ) ; findNum ( a , n , b , m ) ; return 0 ; } |
Generate an array B [ ] from the given array A [ ] which satisfies the given conditions | C ++ implementation of the approach ; Utility function to print the array elements ; Function to generate and print the required array ; To switch the ceil and floor function alternatively ; For every element of the array ; If the number is odd then print the ceil or floor value after division by 2 ; Use the ceil and floor alternatively ; If arr [ i ] is even then it will be completely divisible by 2 ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; void printArr ( int arr [ ] , int n ) { for ( int i = 0 ; i < n ; i ++ ) cout << arr [ i ] << " β " ; } void generateArr ( int arr [ ] , int n ) { bool flip = true ; for ( int i = 0 ; i < n ; i ++ ) { if ( arr [ i ] & 1 ) { if ( flip ^= true ) cout << ceil ( ( float ) ( arr [ i ] ) / 2.0 ) << " β " ; else cout << floor ( ( float ) ( arr [ i ] ) / 2.0 ) << " β " ; } else { cout << arr [ i ] / 2 << " β " ; } } } int main ( ) { int arr [ ] = { 3 , -5 , -7 , 9 , 2 , -2 } ; int n = sizeof ( arr ) / sizeof ( int ) ; generateArr ( arr , n ) ; return 0 ; } |
Number of K length subsequences with minimum sum | C ++ implementation of the approach ; Function to return the value of Binomial Coefficient C ( n , k ) ; Calculate value of Binomial Coefficient in bottom up manner ; Base Cases ; Calculate value using previously stored values ; Function to return the count of valid subsequences ; Sort the array ; Maximum among the minimum K elements ; Y will store the frequency of num in the minimum K elements ; cntX will store the frequency of num in the complete array ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int binomialCoeff ( int n , int k ) { int C [ n + 1 ] [ k + 1 ] ; int i , j ; for ( i = 0 ; i <= n ; i ++ ) { for ( j = 0 ; j <= min ( i , k ) ; j ++ ) { if ( j == 0 j == i ) C [ i ] [ j ] = 1 ; else C [ i ] [ j ] = C [ i - 1 ] [ j - 1 ] + C [ i - 1 ] [ j ] ; } } return C [ n ] [ k ] ; } int cntSubSeq ( int arr [ ] , int n , int k ) { sort ( arr , arr + n ) ; int num = arr [ k - 1 ] ; int Y = 0 ; for ( int i = k - 1 ; i >= 0 ; i -- ) { if ( arr [ i ] == num ) Y ++ ; } int cntX = Y ; for ( int i = k ; i < n ; i ++ ) { if ( arr [ i ] == num ) cntX ++ ; } return binomialCoeff ( cntX , Y ) ; } int main ( ) { int arr [ ] = { 1 , 2 , 3 , 4 } ; int n = sizeof ( arr ) / sizeof ( int ) ; int k = 2 ; cout << cntSubSeq ( arr , n , k ) ; return 0 ; } |
Find all even length binary sequences with same sum of first and second half bits | Iterative | C ++ implementation ; Function to convert the number into binary and store the number into an array ; Function to check if the sum of the digits till the mid of the array and the sum of the digits from mid till n is the same , if they are same then print that binary ; Calculating the sum from 0 till mid and store in sum1 ; Calculating the sum from mid till n and store in sum2 ; If sum1 is same as sum2 print the binary ; Function to print sequence ; Creating the array ; Looping over powers of 2 ; Converting the number into binary first ; Checking if the sum of the first half of the array is same as the sum of the next half ; Driver Code | #include <iostream> NEW_LINE #include <malloc.h> NEW_LINE #include <math.h> NEW_LINE using namespace std ; void convertToBinary ( int num , int a [ ] , int n ) { int pointer = n - 1 ; while ( num > 0 ) { a [ pointer ] = num % 2 ; num = num / 2 ; pointer -- ; } } void checkforsum ( int a [ ] , int n ) { int sum1 = 0 ; int sum2 = 0 ; int mid = n / 2 ; for ( int i = 0 ; i < mid ; i ++ ) sum1 = sum1 + a [ i ] ; for ( int j = mid ; j < n ; j ++ ) sum2 = sum2 + a [ j ] ; if ( sum1 == sum2 ) { for ( int i = 0 ; i < n ; i ++ ) cout << a [ i ] ; cout << " STRNEWLINE " ; } } void print_seq ( int m ) { int n = ( 2 * m ) ; int a [ n ] ; for ( int j = 0 ; j < n ; j ++ ) { a [ j ] = 0 ; } for ( int i = 0 ; i < ( int ) pow ( 2 , n ) ; i ++ ) { convertToBinary ( i , a , n ) ; checkforsum ( a , n ) ; } } int main ( ) { int m = 2 ; print_seq ( m ) ; return 0 ; } |
Find out the prime numbers in the form of A + nB or B + nA | C ++ implementation of the above approach ; Utility function to check whether two numbers is co - prime or not ; Utility function to check whether a number is prime or not ; Corner case ; Check from 2 to sqrt ( n ) ; finding the Prime numbers ; Checking whether given numbers are co - prime or not ; To store the N primes ; If ' possible ' is true ; Printing n numbers of prime ; checking the form of a + nb ; Checking the form of b + na ; If ' possible ' is false return - 1 ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int coprime ( int a , int b ) { if ( __gcd ( a , b ) == 1 ) return true ; else return false ; } bool isPrime ( int n ) { if ( n <= 1 ) return false ; if ( n == 2 or n == 3 ) return true ; for ( int i = 2 ; i * i <= n ; i ++ ) if ( n % i == 0 ) return false ; return true ; } void findNumbers ( int a , int b , int n ) { bool possible = true ; if ( ! coprime ( a , b ) ) possible = false ; int c1 = 1 ; int c2 = 1 ; int num1 , num2 ; set < int > st ; if ( possible ) { while ( ( int ) st . size ( ) != n ) { num1 = a + ( c1 * b ) ; if ( isPrime ( num1 ) ) { st . insert ( num1 ) ; } c1 ++ ; num2 = b + ( c2 * a ) ; if ( isPrime ( num2 ) ) { st . insert ( num2 ) ; } c2 ++ ; } for ( int i : st ) cout << i << " β " ; } else cout << " - 1" ; } int main ( ) { int a = 3 ; int b = 5 ; int n = 4 ; findNumbers ( a , b , n ) ; return 0 ; } |
Find the integers that doesnot ends with T1 or T2 when squared and added X | C ++ program to find the integers that ends with either T1 or T2 when squared and added X ; Function to print the elements Not ending with T1 or T2 ; Flag to check if none of the elements Do not end with t1 or t2 ; Traverse through all the elements ; Temporary variable to store the value ; If the last digit is neither t1 nor t2 then ; Print the number ; Set the flag as False ; If none of the elements meets the specification ; Driver Code ; Test case 1 ; Call the function ; Test case 2 ; Call the function | #include <bits/stdc++.h> NEW_LINE using namespace std ; void findIntegers ( int n , int a [ ] , int x , int t1 , int t2 ) { bool flag = true ; for ( int i = 0 ; i < n ; i ++ ) { int temp = pow ( a [ i ] , 2 ) + x ; if ( temp % 10 != t1 && temp % 10 != t2 ) { cout << temp << " β " ; flag = false ; } } if ( flag ) cout << " - 1" ; } int main ( ) { int N = 4 , X = 10 , T1 = 5 , T2 = 6 ; int a [ N ] = { 3 , 1 , 4 , 7 } ; findIntegers ( N , a , X , T1 , T2 ) ; cout << endl ; N = 4 , X = 2 , T1 = 5 , T2 = 6 ; int b [ N ] = { 2 , 18 , 22 , 8 } ; findIntegers ( N , b , X , T1 , T2 ) ; return 0 ; } |
First N terms whose sum of digits is a multiple of 10 | ; Function to return the sum of digits of n ; Add last digit to the sum ; Remove last digit ; Function to return the nth term of the required series ; If sum of digit is already a multiple of 10 then append 0 ; To store the minimum digit that must be appended ; Return n after appending the required digit ; Function to print the first n terms of the required series ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; const int TEN = 10 ; int digitSum ( int n ) { int sum = 0 ; while ( n > 0 ) { sum += n % TEN ; n /= TEN ; } return sum ; } int getNthTerm ( int n ) { int sum = digitSum ( n ) ; if ( sum % TEN == 0 ) return ( n * TEN ) ; int extra = TEN - ( sum % TEN ) ; return ( ( n * TEN ) + extra ) ; } void firstNTerms ( int n ) { for ( int i = 1 ; i <= n ; i ++ ) cout << getNthTerm ( i ) << " β " ; } int main ( ) { int n = 10 ; firstNTerms ( n ) ; return 0 ; } |
Nearest greater number by interchanging the digits | C ++ program to find nearest greater value ; Find all the possible permutation of Value A . ; Convert into Integer ; Find the minimum value of A by interchanging the digit of A and store min1 . ; Driver code ; Convert integer value into string to find all the permutation of the number ; count = 1 means number greater than B exists | #include <bits/stdc++.h> NEW_LINE using namespace std ; int min1 = INT_MAX ; int _count = 0 ; int permutation ( string str1 , int i , int n , int p ) { if ( i == n ) { int q = stoi ( str1 ) ; if ( q - p > 0 && q < min1 ) { min1 = q ; _count = 1 ; } } else { for ( int j = i ; j <= n ; j ++ ) { swap ( str1 [ i ] , str1 [ j ] ) ; permutation ( str1 , i + 1 , n , p ) ; swap ( str1 [ i ] , str1 [ j ] ) ; } } return min1 ; } int main ( ) { int A = 213 ; int B = 111 ; string str1 = to_string ( A ) ; int len = str1 . length ( ) ; int h = permutation ( str1 , 0 , len - 1 , B ) ; _count ? cout << h << endl : cout << -1 << endl ; return 0 ; } |
Alcuin 's Sequence | CPP program for Alcuin 's Sequence ; find the nth term of Alcuin 's sequence ; return the ans ; print first n terms of Alcuin number ; display the number ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int Alcuin ( int n ) { double _n = n , ans ; ans = round ( ( _n * _n ) / 12 ) - floor ( _n / 4 ) * floor ( ( _n + 2 ) / 4 ) ; return ans ; } void solve ( int n ) { int i = 0 ; for ( int i = 1 ; i <= n ; i ++ ) { cout << Alcuin ( i ) << " , β " ; } } int main ( ) { int n = 15 ; solve ( n ) ; return 0 ; } |
Find the final sequence of the array after performing given operations | C ++ implementation of the approach ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int * solve ( int arr [ ] , int n ) { static int b [ 4 ] ; int p = 0 ; for ( int i = n - 1 ; i >= 0 ; i -- ) { b [ p ] = arr [ i -- ] ; if ( i >= 0 ) b [ n - 1 - p ] = arr [ i ] ; p ++ ; } return b ; } int main ( ) { int arr [ ] = { 1 , 2 , 3 , 4 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; int * b ; b = solve ( arr , n ) ; for ( int i = 0 ; i < n ; i ++ ) cout << b [ i ] << " β " ; } |
Check if the product of every contiguous subsequence is different or not in a number | C ++ implementation of the approach ; Function that returns true if the product of every digit of a contiguous subsequence is distinct ; To store the given number as a string ; Append all the digits starting from the end ; Reverse the string to get the original number ; Store size of the string ; Set to store product of each contiguous subsequence ; Find product of every contiguous subsequence ; If current product already exists in the set ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; bool productsDistinct ( int N ) { string s = " " ; while ( N ) { s += ( char ) ( N % 10 + '0' ) ; N /= 10 ; } reverse ( s . begin ( ) , s . end ( ) ) ; int sz = s . size ( ) ; set < int > se ; for ( int i = 0 ; i < sz ; i ++ ) { int product = 1 ; for ( int j = i ; j < sz ; j ++ ) { product *= ( int ) ( s [ j ] - '0' ) ; if ( se . find ( product ) != se . end ( ) ) return false ; else se . insert ( product ) ; } } return true ; } int main ( ) { int N = 2345 ; if ( productsDistinct ( N ) ) cout << " Yes " ; else cout << " No " ; return 0 ; } |
Number of ways to arrange 2 * N persons on the two sides of a table with X and Y persons on opposite sides | ; Function to find factorial of a number ; Function to find nCr ; Function to find the number of ways to arrange 2 * N persons ; Driver code ; Function call | #include <bits/stdc++.h> NEW_LINE using namespace std ; int factorial ( int n ) { if ( n <= 1 ) return 1 ; return n * factorial ( n - 1 ) ; } int nCr ( int n , int r ) { return factorial ( n ) / ( factorial ( n - r ) * factorial ( r ) ) ; } int NumberOfWays ( int n , int x , int y ) { return nCr ( 2 * n - x - y , n - x ) * factorial ( n ) * factorial ( n ) ; } int main ( ) { int n = 5 , x = 4 , y = 2 ; cout << NumberOfWays ( n , x , y ) ; return 0 ; } |
Find smallest positive number Y such that Bitwise AND of X and Y is Zero | C ++ program to find smallest number Y for a given value of X such that X AND Y is zero ; Method to find smallest number Y for a given value of X such that X AND Y is zero ; Convert the number into its binary form ; Case 1 : If all bits are ones , then return the next number ; Case 2 : find the first 0 - bit index and return the Y ; Driver Code | #include <bits/stdc++.h> NEW_LINE #define mod 1000000007 NEW_LINE using namespace std ; int findSmallestNonZeroY ( int A_num ) { string A_binary = bitset < 8 > ( A_num ) . to_string ( ) ; int B = 1 ; int length = A_binary . size ( ) ; int no_ones = __builtin_popcount ( A_num ) ; if ( length == no_ones ) return A_num + 1 ; for ( int i = 0 ; i < length ; i ++ ) { char ch = A_binary [ length - i - 1 ] ; if ( ch == '0' ) { B = pow ( 2.0 , i ) ; break ; } } return B ; } int main ( ) { int X = findSmallestNonZeroY ( 10 ) ; cout << X ; } |
Count number of set bits in a range using bitset | C ++ implementation of above approach ; function to count number of 1 's using bitset ; Converting the string into bitset ; Bitwise operations Left shift ; Right shifts ; return count of one in [ L , R ] ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; #define N 32 NEW_LINE int GetOne ( string s , int L , int R ) { int len = s . length ( ) ; bitset < N > bit ( s ) ; bit <<= ( N - len + L - 1 ) ; bit >>= ( N - len + L - 1 ) ; bit >>= ( len - R ) ; return bit . count ( ) ; } int main ( ) { string s = "01010001011" ; int L = 2 , R = 4 ; cout << GetOne ( s , L , R ) ; return 0 ; } |
Maximum element in an array such that its previous and next element product is maximum | ; Function to return the largest element such that its previous and next element product is maximum ; Calculate the product of the previous and the next element for the current element ; Update the maximum product ; If current product is equal to the current maximum product then choose the maximum element ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int maxElement ( int a [ ] , int n ) { if ( n < 3 ) return -1 ; int maxElement = a [ 0 ] ; int maxProd = a [ n - 1 ] * a [ 1 ] ; for ( int i = 1 ; i < n ; i ++ ) { int currProd = a [ i - 1 ] * a [ ( i + 1 ) % n ] ; if ( currProd > maxProd ) { maxProd = currProd ; maxElement = a [ i ] ; } else if ( currProd == maxProd ) { maxElement = max ( maxElement , a [ i ] ) ; } } return maxElement ; } int main ( ) { int a [ ] = { 5 , 6 , 4 , 3 , 2 } ; int n = sizeof ( a ) / sizeof ( a [ 0 ] ) ; cout << maxElement ( a , n ) ; return 0 ; } |
Total ways of choosing X men and Y women from a total of M men and W women | C ++ implementation of the approach ; Function to return the value of ncr effectively ; Initialize the answer ; Divide simultaneously by i to avoid overflow ; Function to return the count of required ways ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int ncr ( int n , int r ) { int ans = 1 ; for ( int i = 1 ; i <= r ; i += 1 ) { ans *= ( n - r + i ) ; ans /= i ; } return ans ; } int totalWays ( int X , int Y , int M , int W ) { return ( ncr ( M , X ) * ncr ( W , Y ) ) ; } int main ( ) { int X = 4 , Y = 3 , M = 6 , W = 5 ; cout << totalWays ( X , Y , M , W ) ; return 0 ; } |
Generate elements of the array following given conditions | C ++ implementation of the approach ; Function to generate the required array ; Initialize cnt variable for assigning unique value to prime and its multiples ; When we get a prime for the first time then assign a unique smallest value to it and all of its multiples ; Print the generated array ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; void specialSieve ( int n ) { int cnt = 0 ; int prime [ n + 1 ] ; for ( int i = 0 ; i <= n ; i ++ ) prime [ i ] = 0 ; for ( int i = 2 ; i <= n ; i ++ ) { if ( ! prime [ i ] ) { cnt ++ ; for ( int j = i ; j <= n ; j += i ) prime [ j ] = cnt ; } } for ( int i = 2 ; i <= n ; i ++ ) cout << prime [ i ] << " β " ; } int main ( ) { int n = 6 ; specialSieve ( n ) ; return 0 ; } |
Find the node whose sum with X has maximum set bits | C ++ implementation of the approach ; Function to perform dfs to find the maximum set bits value ; If current set bits value is greater than the current maximum ; If count is equal to the maximum then choose the node with minimum value ; Driver code ; Weights of the node ; Edges of the tree | #include <bits/stdc++.h> NEW_LINE using namespace std ; int maximum = INT_MIN , x , ans = INT_MAX ; vector < int > graph [ 100 ] ; vector < int > weight ( 100 ) ; void dfs ( int node , int parent ) { int a = __builtin_popcount ( weight [ node ] + x ) ; if ( maximum < a ) { maximum = a ; ans = node ; } else if ( maximum == a ) ans = min ( ans , node ) ; for ( int to : graph [ node ] ) { if ( to == parent ) continue ; dfs ( to , node ) ; } } int main ( ) { x = 15 ; weight [ 1 ] = 5 ; weight [ 2 ] = 10 ; weight [ 3 ] = 11 ; weight [ 4 ] = 8 ; weight [ 5 ] = 6 ; graph [ 1 ] . push_back ( 2 ) ; graph [ 2 ] . push_back ( 3 ) ; graph [ 2 ] . push_back ( 4 ) ; graph [ 1 ] . push_back ( 5 ) ; dfs ( 1 , 1 ) ; cout << ans ; return 0 ; } |
Count Pairs from two arrays with even sum | C ++ implementation of the approach ; Function to return count of required pairs ; Count of odd and even numbers from both the arrays ; Find the count of odd and even elements in a [ ] ; Find the count of odd and even elements in b [ ] ; Count the number of pairs ; Return the number of pairs ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int count_pairs ( int a [ ] , int b [ ] , int n , int m ) { int odd1 = 0 , even1 = 0 ; int odd2 = 0 , even2 = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( a [ i ] % 2 == 1 ) odd1 ++ ; else even1 ++ ; } for ( int i = 0 ; i < m ; i ++ ) { if ( b [ i ] % 2 == 1 ) odd2 ++ ; else even2 ++ ; } int pairs = min ( odd1 , odd2 ) + min ( even1 , even2 ) ; return pairs ; } int main ( ) { int a [ ] = { 9 , 14 , 6 , 2 , 11 } ; int b [ ] = { 8 , 4 , 7 , 20 } ; int n = sizeof ( a ) / sizeof ( a [ 0 ] ) ; int m = sizeof ( b ) / sizeof ( b [ 0 ] ) ; cout << count_pairs ( a , b , n , m ) ; return 0 ; } |
Find an index such that difference between product of elements before and after it is minimum | ; Function to find index ; Array to store log values of elements ; Prefix Array to Maintain Sum of log values till index i ; Answer Index ; Find minimum absolute value ; Driver Code | #include <bits/stdc++.h> NEW_LINE #define ll long long int NEW_LINE using namespace std ; void solve ( int Array [ ] , int N ) { double Arraynew [ N ] ; for ( int i = 0 ; i < N ; i ++ ) { Arraynew [ i ] = log ( Array [ i ] ) ; } double prefixsum [ N ] ; prefixsum [ 0 ] = Arraynew [ 0 ] ; for ( int i = 1 ; i < N ; i ++ ) { prefixsum [ i ] = prefixsum [ i - 1 ] + Arraynew [ i ] ; } int answer = 0 ; double minabs = abs ( prefixsum [ N - 1 ] - 2 * prefixsum [ 0 ] ) ; for ( int i = 1 ; i < N - 1 ; i ++ ) { double ans1 = abs ( prefixsum [ N - 1 ] - 2 * prefixsum [ i ] ) ; if ( ans1 < minabs ) { minabs = ans1 ; answer = i ; } } cout << " Index β is : β " << answer << endl ; } int main ( ) { int Array [ 5 ] = { 1 , 4 , 12 , 2 , 6 } ; int N = 5 ; solve ( Array , N ) ; } |
Find the value of N when F ( N ) = f ( a ) + f ( b ) where a + b is the minimum possible and a * b = N | C ++ implementation of the approach ; Function to return the value of F ( N ) ; Base cases ; Count the number of times a number if divisible by 2 ; Return the summation ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int getValueOfF ( int n ) { if ( n == 1 ) return 0 ; if ( n == 2 ) return 1 ; int cnt = 0 ; while ( n % 2 == 0 ) { cnt += 1 ; n /= 2 ; } return 2 * cnt ; } int main ( ) { int n = 20 ; cout << getValueOfF ( n ) ; return 0 ; } |
Find the sum of the number of divisors | ; To store the number of divisors ; Function to find the number of divisors of all numbers in the range 1 to n ; For every number 1 to n ; Increase divisors count for every number ; Function to find the sum of divisors ; To store sum ; Count the divisors ; Driver code ; Function call | #include <bits/stdc++.h> NEW_LINE using namespace std ; #define N 100005 NEW_LINE #define mod 1000000007 NEW_LINE int cnt [ N ] ; void Divisors ( ) { memset ( cnt , 0 , sizeof cnt ) ; for ( int i = 1 ; i < N ; i ++ ) { for ( int j = 1 ; j * i < N ; j ++ ) cnt [ i * j ] ++ ; } } int Sumofdivisors ( int A , int B , int C ) { int sum = 0 ; Divisors ( ) ; for ( int i = 1 ; i <= A ; i ++ ) { for ( int j = 1 ; j <= B ; j ++ ) { for ( int k = 1 ; k <= C ; k ++ ) { int x = i * j * k ; sum += cnt [ x ] ; if ( sum >= mod ) sum -= mod ; } } } return sum ; } int main ( ) { int A = 5 , B = 6 , C = 7 ; cout << Sumofdivisors ( A , B , C ) ; return 0 ; } |
Find ( 1 ^ n + 2 ^ n + 3 ^ n + 4 ^ n ) mod 5 | Set 2 | C ++ implementation of the approach ; Function to return A mod B ; length of the string ; to store required answer ; Function to return ( 1 ^ n + 2 ^ n + 3 ^ n + 4 ^ n ) % 5 ; Calculate and return ans ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int A_mod_B ( string N , int a ) { int len = N . size ( ) ; int ans = 0 ; for ( int i = 0 ; i < len ; i ++ ) ans = ( ans * 10 + ( int ) N [ i ] - '0' ) % a ; return ans % a ; } int findMod ( string N ) { int mod = A_mod_B ( N , 4 ) ; int ans = ( 1 + pow ( 2 , mod ) + pow ( 3 , mod ) + pow ( 4 , mod ) ) ; return ( ans % 5 ) ; } int main ( ) { string N = "4" ; cout << findMod ( N ) ; return 0 ; } |
Elements greater than the previous and next element in an Array | C ++ program to print elements greater than the previous and next element in an Array ; Function to print elements greater than the previous and next element in an Array ; Traverse array from index 1 to n - 2 and check for the given condition ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; void printElements ( int arr [ ] , int n ) { for ( int i = 1 ; i < n - 1 ; i ++ ) { if ( arr [ i ] > arr [ i - 1 ] and arr [ i ] > arr [ i + 1 ] ) cout << arr [ i ] << " β " ; } } int main ( ) { int arr [ ] = { 2 , 3 , 1 , 5 , 4 , 9 , 8 , 7 , 5 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; printElements ( arr , n ) ; return 0 ; } |
Sum of the series Kn + ( K ( n | CPP program of above approach ; Recursive C program to compute modular power ; Base cases ; If B is even ; If B is odd ; Function to return sum ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int exponent ( int A , int B ) { if ( A == 0 ) return 0 ; if ( B == 0 ) return 1 ; long y ; if ( B % 2 == 0 ) { y = exponent ( A , B / 2 ) ; y = ( y * y ) ; } else { y = A ; y = ( y * exponent ( A , B - 1 ) ) ; } return y ; } int sum ( int k , int n ) { int sum = exponent ( k , n + 1 ) - exponent ( k - 1 , n + 1 ) ; return sum ; } int main ( ) { int n = 3 ; int K = 3 ; cout << sum ( K , n ) ; } |
Minimize the cost to split a number | C ++ implementation of the approach ; check if a number is prime or not ; run a loop upto square root of x ; Function to return the minimized cost ; If n is prime ; If n is odd and can be split into ( prime + 2 ) then cost will be 1 + 1 = 2 ; Every non - prime even number can be expressed as the sum of two primes ; n is odd so n can be split into ( 3 + even ) further even part can be split into ( prime + prime ) ( 3 + prime + prime ) will cost 3 ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; bool isPrime ( int x ) { for ( int i = 2 ; i * i <= x ; i ++ ) { if ( x % i == 0 ) return 0 ; } return 1 ; } int minimumCost ( int n ) { if ( isPrime ( n ) ) return 1 ; if ( n % 2 == 1 && isPrime ( n - 2 ) ) return 2 ; if ( n % 2 == 0 ) return 2 ; return 3 ; } int main ( ) { int n = 6 ; cout << minimumCost ( n ) ; return 0 ; } |
Find amount of water wasted after filling the tank | C ++ program to find the volume of water wasted ; Function to calculate amount of wasted water ; filled amount of water in one minute ; total time taken to fill the tank because of leakage ; wasted amount of water ; Driver code | #include <iostream> NEW_LINE using namespace std ; double wastedWater ( double V , double M , double N ) { double wasted_amt , amt_per_min , time_to_fill ; amt_per_min = M - N ; time_to_fill = V / amt_per_min ; wasted_amt = N * time_to_fill ; return wasted_amt ; } int main ( ) { double V , M , N ; V = 700 ; M = 10 ; N = 3 ; cout << wastedWater ( V , M , N ) << endl ; V = 1000 ; M = 100 ; N = 50 ; cout << wastedWater ( V , M , N ) << endl ; return 0 ; } |
Smallest and Largest N | C ++ implementation of the approach ; Function to print the largest and the smallest n - digit perfect cube ; Smallest n - digit perfect cube ; Largest n - digit perfect cube ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; void nDigitPerfectCubes ( int n ) { cout << pow ( ceil ( cbrt ( pow ( 10 , ( n - 1 ) ) ) ) , 3 ) << " β " ; cout << ( int ) pow ( ceil ( cbrt ( pow ( 10 , ( n ) ) ) ) - 1 , 3 ) ; } int main ( ) { int n = 3 ; nDigitPerfectCubes ( n ) ; return 0 ; } |
Count numbers which are divisible by all the numbers from 2 to 10 | C ++ implementation of the approach ; Function to return the count of numbers from 1 to n which are divisible by all the numbers from 2 to 10 ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int countNumbers ( int n ) { return ( n / 2520 ) ; } int main ( ) { int n = 3000 ; cout << countNumbers ( n ) ; return 0 ; } |
Sum of all odd factors of numbers in the range [ l , r ] | C ++ implementation of the approach ; Function to calculate the prefix sum of all the odd factors ; Add i to all the multiples of i ; Update the prefix sum ; Function to return the sum of all the odd factors of the numbers in the given range ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; #define ll long long int NEW_LINE const int MAX = 100001 ; ll prefix [ MAX ] ; void sieve_modified ( ) { for ( int i = 1 ; i < MAX ; i += 2 ) { for ( int j = i ; j < MAX ; j += i ) prefix [ j ] += i ; } for ( int i = 1 ; i < MAX ; i ++ ) prefix [ i ] += prefix [ i - 1 ] ; } ll sumOddFactors ( int L , int R ) { return ( prefix [ R ] - prefix [ L - 1 ] ) ; } int main ( ) { sieve_modified ( ) ; int l = 6 , r = 10 ; cout << sumOddFactors ( l , r ) ; return 0 ; } |
Number of ways in which an item returns back to its initial position in N swaps in array of size K | C ++ program to find the number of ways in which an item returns back to its initial position in N swaps in an array of size K ; Function to calculate ( x ^ y ) % p in O ( log y ) ; Initialize result ; Update x if it is more than or equal to p ; If y is odd , multiply x with result ; y must be even now y = y / 2 ; Function to return the number of ways ; Base case ; Recursive case F ( n ) = ( k - 1 ) ^ ( n - 1 ) - F ( n - 1 ) . ; Drivers code ; Function calling | #include <bits/stdc++.h> NEW_LINE using namespace std ; #define mod 1000000007 NEW_LINE long long power ( long x , long y ) { long p = mod ; long res = 1 ; x = x % p ; while ( y > 0 ) { if ( y & 1 ) res = ( res * x ) % p ; y = y >> 1 ; x = ( x * x ) % p ; } return res ; } long long solve ( int n , int k ) { if ( n == 1 ) return 0LL ; return ( power ( ( k - 1 ) , n - 1 ) % mod - solve ( n - 1 , k ) + mod ) % mod ; } int main ( ) { int n = 4 , k = 5 ; cout << solve ( n , k ) ; return 0 ; } |
XOR of a submatrix queries | C ++ implementation of the approach ; Function to pre - compute the xor ; Left to right prefix xor for each row ; Top to bottom prefix xor for each column ; Function to process the queries x1 , x2 , y1 , y2 represent the positions of the top - left and bottom right corners ; To store the xor values ; Finding the values we need to xor with value at ( x2 , y2 ) in prefix - xor matrix ; Return the required prefix xor ; Driver code ; To store pre - computed xor ; Pre - computing xor ; Queries | #include <iostream> NEW_LINE #define n 3 NEW_LINE using namespace std ; void preComputeXor ( int arr [ ] [ n ] , int prefix_xor [ ] [ n ] ) { for ( int i = 0 ; i < n ; i ++ ) for ( int j = 0 ; j < n ; j ++ ) { if ( j == 0 ) prefix_xor [ i ] [ j ] = arr [ i ] [ j ] ; else prefix_xor [ i ] [ j ] = ( prefix_xor [ i ] [ j - 1 ] ^ arr [ i ] [ j ] ) ; } for ( int i = 0 ; i < n ; i ++ ) for ( int j = 1 ; j < n ; j ++ ) prefix_xor [ j ] [ i ] = ( prefix_xor [ j - 1 ] [ i ] ^ prefix_xor [ j ] [ i ] ) ; } int ansQuerie ( int prefix_xor [ ] [ n ] , int x1 , int y1 , int x2 , int y2 ) { int xor_1 = 0 , xor_2 = 0 , xor_3 = 0 ; if ( x1 != 0 ) xor_1 = prefix_xor [ x1 - 1 ] [ y2 ] ; if ( y1 != 0 ) xor_2 = prefix_xor [ x2 ] [ y1 - 1 ] ; if ( x1 != 0 and y1 != 0 ) xor_3 = prefix_xor [ x1 - 1 ] [ y1 - 1 ] ; return ( ( prefix_xor [ x2 ] [ y2 ] ^ xor_1 ) ^ ( xor_2 ^ xor_3 ) ) ; } int main ( ) { int arr [ ] [ n ] = { { 1 , 2 , 3 } , { 4 , 5 , 6 } , { 7 , 8 , 9 } } ; int prefix_xor [ n ] [ n ] ; preComputeXor ( arr , prefix_xor ) ; cout << ansQuerie ( prefix_xor , 1 , 1 , 2 , 2 ) << endl ; cout << ansQuerie ( prefix_xor , 1 , 2 , 2 , 2 ) << endl ; return 0 ; } |
Numbers less than N that are perfect cubes and the sum of their digits reduced to a single digit is 1 | C ++ implementation of the approach ; Function that returns true if the eventual digit sum of number nm is 1 ; if reminder will 1 then eventual sum is 1 ; Function to print the required numbers less than n ; If it is the required perfect cube ; Driver code | #include <cmath> NEW_LINE #include <iostream> NEW_LINE using namespace std ; bool isDigitSumOne ( int nm ) { if ( nm % 9 == 1 ) return true ; else return false ; } void printValidNums ( int n ) { int cbrt_n = ( int ) cbrt ( n ) ; for ( int i = 1 ; i <= cbrt_n ; i ++ ) { int cube = pow ( i , 3 ) ; if ( cube >= 1 && cube <= n && isDigitSumOne ( cube ) ) cout << cube << " β " ; } } int main ( ) { int n = 1000 ; printValidNums ( n ) ; return 0 ; } |
Count the number of rhombi possible inside a rectangle of given size | C ++ implementation of the approach ; Function to return the count of rhombi possible ; All possible diagonal lengths ; Update rhombi possible with the current diagonal lengths ; Return the total count of rhombi possible ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; long long countRhombi ( int h , int w ) { long long ct = 0 ; for ( int i = 2 ; i <= h ; i += 2 ) for ( int j = 2 ; j <= w ; j += 2 ) ct += ( h - i + 1 ) * ( w - j + 1 ) ; return ct ; } int main ( ) { int h = 2 , w = 2 ; cout << countRhombi ( h , w ) ; return 0 ; } |
Program to calculate the area between two Concentric Circles | C ++ program to find area between the two given concentric circles ; Function to find area between the two given concentric circles ; Declare value of pi ; Calculate area of outer circle ; Calculate area of inner circle ; Difference in areas ; Driver Program | #include <bits/stdc++.h> NEW_LINE using namespace std ; double calculateArea ( int x , int y ) { double pi = 3.1415926536 ; double arx = pi * x * x ; double ary = pi * y * y ; return arx - ary ; } int main ( ) { int x = 2 ; int y = 1 ; cout << calculateArea ( x , y ) ; return 0 ; } |
Find the winner by adding Pairwise difference of elements in the array until Possible | C ++ implementation of the approach ; Function to return the winner of the game ; To store the gcd of the original array ; To store the maximum element from the original array ; If number of moves are odd ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; char getWinner ( int arr [ ] , int n ) { int gcd = arr [ 0 ] ; int maxEle = arr [ 0 ] ; for ( int i = 1 ; i < n ; i ++ ) { gcd = __gcd ( gcd , arr [ i ] ) ; maxEle = max ( maxEle , arr [ i ] ) ; } int totalMoves = ( maxEle / gcd ) - n ; if ( totalMoves % 2 == 1 ) return ' A ' ; return ' B ' ; } int main ( ) { int arr [ ] = { 5 , 6 , 7 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << getWinner ( arr , n ) ; return 0 ; } |
Count of pairs of ( i , j ) such that ( ( n % i ) % j ) % n is maximized | CPP implementation of the approach ; Function to return the count of required pairs ; Number which will give the max value for ( ( n % i ) % j ) % n ; To store the maximum possible value of ( ( n % i ) % j ) % n ; To store the count of possible pairs ; Check all possible pairs ; Calculating the value of ( ( n % i ) % j ) % n ; If value is equal to maximum ; Return the number of possible pairs ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int countPairs ( int n ) { int num = ( ( n / 2 ) + 1 ) ; int max = n % num ; int count = 0 ; for ( int i = 1 ; i <= n ; i ++ ) { for ( int j = 1 ; j <= n ; j ++ ) { int val = ( ( n % i ) % j ) % n ; if ( val == max ) count ++ ; } } return count ; } int main ( ) { int n = 5 ; cout << ( countPairs ( n ) ) ; } |
Program to check if a number is divisible by any of its digits | C ++ implementation of above approach ; Function to check if given number is divisible by any of its digits ; check if any of digit divides n ; check if K divides N ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; string isDivisible ( long long int n ) { long long int temp = n ; while ( n ) { int k = n % 10 ; if ( temp % k == 0 ) return " YES " ; n /= 10 ; } return " NO " ; } int main ( ) { long long int n = 9876543 ; cout << isDivisible ( n ) ; return 0 ; } |
Program to find sum of harmonic series | C ++ program to find sum of harmonic series ; Function to return sum of harmonic series ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; double sum ( int n ) { double i , s = 0.0 ; for ( i = 1 ; i <= n ; i ++ ) s = s + 1 / i ; return s ; } int main ( ) { int n = 5 ; cout << " Sum β is β " << sum ( n ) ; return 0 ; } |
Check if a number can be expressed as sum two abundant numbers | CPP program to check if number n is expressed as sum of two abundant numbers ; Function to return all abundant numbers This function will be helpful for multiple queries ; To store abundant numbers ; to store sum of the divisors include 1 in the sum ; if j is proper divisor ; if i is not a perfect square ; if sum is greater than i then i is a abundant number ; Check if number n is expressed as sum of two abundant numbers ; if both i and n - i are abundant numbers ; can not be expressed ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; #define N 100005 NEW_LINE set < int > ABUNDANT ( ) { set < int > v ; for ( int i = 1 ; i < N ; i ++ ) { int sum = 1 ; for ( int j = 2 ; j * j <= i ; j ++ ) { if ( i % j == 0 ) { sum += j ; if ( i / j != j ) sum += i / j ; } } if ( sum > i ) v . insert ( i ) ; } return v ; } void SumOfAbundant ( int n ) { set < int > v = ABUNDANT ( ) ; for ( int i = 1 ; i <= n ; i ++ ) { if ( v . count ( i ) and v . count ( n - i ) ) { cout << i << " β " << n - i ; return ; } } cout << -1 ; } int main ( ) { int n = 24 ; SumOfAbundant ( n ) ; return 0 ; } |
Find nth term of the series 5 2 13 41 | C ++ program to find nth term of the series 5 2 13 41 ; function to calculate nth term of the series ; to store the nth term of series ; if n is even number ; if n is odd number ; return nth term ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int nthTermOfTheSeries ( int n ) { int nthTerm ; if ( n % 2 == 0 ) nthTerm = pow ( n - 1 , 2 ) + n ; else nthTerm = pow ( n + 1 , 2 ) + n ; return nthTerm ; } int main ( ) { int n ; n = 8 ; cout << nthTermOfTheSeries ( n ) << endl ; n = 12 ; cout << nthTermOfTheSeries ( n ) << endl ; n = 102 ; cout << nthTermOfTheSeries ( n ) << endl ; n = 999 ; cout << nthTermOfTheSeries ( n ) << endl ; n = 9999 ; cout << nthTermOfTheSeries ( n ) << endl ; return 0 ; } |
Find cost price from given selling price and profit or loss percentage | C ++ implementation to find Cost price ; Function to calculate cost price with profit ; required formula to calculate CP with profit ; Function to calculate cost price with loss ; required formula to calculate CP with loss ; Driver code | #include <iostream> NEW_LINE using namespace std ; float CPwithProfit ( int sellingPrice , int profit ) { float costPrice ; costPrice = ( sellingPrice * 100.0 ) / ( 100 + profit ) ; return costPrice ; } float CPwithLoss ( int sellingPrice , int loss ) { float costPrice ; costPrice = ( sellingPrice * 100.0 ) / ( 100 - loss ) ; return costPrice ; } int main ( ) { int SP , profit , loss ; SP = 1020 ; profit = 20 ; cout << " Cost β Price β = β " << CPwithProfit ( SP , profit ) << endl ; SP = 900 ; loss = 10 ; cout << " Cost β Price β = β " << CPwithLoss ( SP , loss ) << endl ; SP = 42039 ; profit = 8 ; cout << " Cost β Price β = β " << CPwithProfit ( SP , profit ) << endl ; return 0 ; } |
Check whether a number is Non | CPP program to check if a given number is Non - Hypotenuse number or not . ; Function to find prime factor and check if it is of the form 4 k + 1 or not ; 2 is a prime number but not of the form 4 k + 1 so , keep Dividing n by 2 until n is divisible by 2 ; n must be odd at this point . So we can skip one element ( Note i = i + 2 ) ; if i divides n check if i is of the form 4 k + 1 or not ; while i divides n divide n by i and update n ; This condition is to handle the case when n is a prime number greater than 2 ; Test function ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; bool isNonHypotenuse ( int n ) { while ( n % 2 == 0 ) { n = n / 2 ; } for ( int i = 3 ; i <= sqrt ( n ) ; i = i + 2 ) { if ( n % i == 0 ) { if ( ( i - 1 ) % 4 == 0 ) return false ; while ( n % i == 0 ) { n = n / i ; } } } if ( n > 2 && ( n - 1 ) % 4 == 0 ) return false ; else return true ; } void test ( int n ) { cout << " Testing β for β " << n << " β : β " ; if ( isNonHypotenuse ( n ) ) cout << " YES " << " STRNEWLINE " ; else cout << " NO " << " STRNEWLINE " ; } int main ( ) { int n = 11 ; test ( n ) ; n = 10 ; test ( n ) ; return 0 ; } |
Find the n | C ++ implementation of the above approach ; Function to return the nth string in the required sequence ; Length of the resultant string ; Relative index ; Initial string of length len consists of all a 's since the list is sorted ; Convert relative index to Binary form and set 0 = a and 1 = b ; Reverse and return the string ; Driver function | #include <bits/stdc++.h> NEW_LINE using namespace std ; #define ll long long int NEW_LINE string obtain_str ( ll n ) { ll len = ( int ) log2 ( n + 1 ) ; ll rel_ind = n + 1 - pow ( 2 , len ) ; ll i = 0 ; string str = " " ; for ( i = 0 ; i < len ; i ++ ) { str += ' a ' ; } i = 0 ; while ( rel_ind > 0 ) { if ( rel_ind % 2 == 1 ) str [ i ] = ' b ' ; rel_ind /= 2 ; i ++ ; } reverse ( str . begin ( ) , str . end ( ) ) ; return str ; } int main ( ) { ll n = 11 ; cout << obtain_str ( n ) ; return 0 ; } |
Program to find the Nth term of the series 0 , 3 / 1 , 8 / 3 , 15 / 5. . ... ... | C ++ implementation of the approach ; Function to return the nth term of the given series ; nth term ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; void Nthterm ( int n ) { int numerator = pow ( n , 2 ) - 1 ; int denomenator = 2 * n - 3 ; cout << numerator << " / " << denomenator ; } int main ( ) { int n = 3 ; Nthterm ( n ) ; return 0 ; } |
Sum of each element raised to ( prime | C ++ implementation of the approach ; Function to return the required sum ; Driver code | #include <iostream> NEW_LINE #include <vector> NEW_LINE using namespace std ; int getSum ( vector < int > arr , int p ) { return arr . size ( ) ; } int main ( ) { vector < int > arr = { 5 , 6 , 8 } ; int p = 7 ; cout << getSum ( arr , p ) << endl ; return 0 ; } |
Count numbers upto N which are both perfect square and perfect cube | C ++ implementation of the above approach ; Function to return required count ; Driver code ; function call to print required answer | #include <bits/stdc++.h> NEW_LINE using namespace std ; int SquareCube ( long long int N ) { int cnt = 0 , i = 1 ; while ( int ( pow ( i , 6 ) ) <= N ) { ++ cnt ; ++ i ; } return cnt ; } int main ( ) { long long int N = 100000 ; cout << SquareCube ( N ) ; return 0 ; } |
Sum of integers upto N with given unit digit | C ++ implementation of the approach ; Function to return the required sum ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; #define ll long long int NEW_LINE ll getSum ( int n , int d ) { ll sum = 0 ; while ( d <= n ) { sum += d ; d += 10 ; } return sum ; } int main ( ) { int n = 30 , d = 3 ; cout << getSum ( n , d ) ; return 0 ; } |
Summing the sum series | C ++ program to calculate the terms of summing of sum series ; Function to calculate twice of sum of first N natural numbers ; Function to calculate the terms of summing of sum series ; Driver Code | #include <iostream> NEW_LINE using namespace std ; # define MOD 1000000007 NEW_LINE long sum ( long N ) { long val = N * ( N + 1 ) ; val = val % MOD ; return val ; } int sumX ( int N , int M , int K ) { for ( int i = 0 ; i < M ; i ++ ) { N = ( int ) sum ( K + N ) ; } N = N % MOD ; return N ; } int main ( ) { int N = 1 , M = 2 , K = 3 ; cout << sumX ( N , M , K ) << endl ; return 0 ; } |
Logarithm | C ++ program to find log ( n ) using Recursion ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; unsigned int Log2n ( unsigned int n ) { return ( n > 1 ) ? 1 + Log2n ( n / 2 ) : 0 ; } int main ( ) { unsigned int n = 32 ; cout << Log2n ( n ) << " STRNEWLINE " ; return 0 ; } |
Mode | C ++ Program for Mode using Counting Sort technique ; Function that sort input array a [ ] and calculate mode and median using counting sort . ; The output array b [ ] will have sorted array ; variable to store max of input array which will to have size of count array ; auxiliary ( count ) array to store count . Initialize count array as 0. Size of count array will be equal to ( max + 1 ) . ; Store count of each element of input array ; mode is the index with maximum count ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; void printMode ( int a [ ] , int n ) { int b [ n ] ; int max = * max_element ( a , a + n ) ; int t = max + 1 ; int count [ t ] ; for ( int i = 0 ; i < t ; i ++ ) count [ i ] = 0 ; for ( int i = 0 ; i < n ; i ++ ) count [ a [ i ] ] ++ ; int mode = 0 ; int k = count [ 0 ] ; for ( int i = 1 ; i < t ; i ++ ) { if ( count [ i ] > k ) { k = count [ i ] ; mode = i ; } } cout << " mode β = β " << mode ; } int main ( ) { int a [ ] = { 1 , 4 , 1 , 2 , 7 , 1 , 2 , 5 , 3 , 6 } ; int n = sizeof ( a ) / sizeof ( a [ 0 ] ) ; printMode ( a , n ) ; return 0 ; } |
Harmonic Progression | CPP program to check if a given array can form harmonic progression ; Find reciprocal of arr [ ] ; After finding reciprocal , check if the reciprocal is in A . P . To check for A . P . , first Sort the reciprocal array , then check difference between consecutive elements ; Driver Code ; series to check whether it is in H . P ; Checking a series is in H . P or not | #include <bits/stdc++.h> NEW_LINE using namespace std ; bool checkIsHP ( vector < double > & arr ) { int n = arr . size ( ) ; if ( n == 1 ) { return true ; } vector < int > rec ; for ( int i = 0 ; i < n ; i ++ ) { rec . push_back ( ( 1 / arr [ i ] ) ) ; } sort ( rec . begin ( ) , rec . end ( ) ) ; int d = ( rec [ 1 ] ) - ( rec [ 0 ] ) ; for ( int i = 2 ; i < n ; i ++ ) { if ( rec [ i ] - rec [ i - 1 ] != d ) { return false ; } } return true ; } int main ( ) { vector < double > arr = { 1 / 5 , 1 / 10 , 1 / 15 , 1 / 20 , 1 / 25 } ; if ( checkIsHP ( arr ) ) { cout << " Yes " << std :: endl ; } else { cout << " No " << endl ; } return 0 ; } |
Arithmetic Mean | C ++ program to find n arithmetic means between A and B ; Prints N arithmetic means between A and B . ; calculate common difference ( d ) ; for finding N the arithmetic mean between A and B ; Driver code to test above | #include <bits/stdc++.h> NEW_LINE using namespace std ; void printAMeans ( int A , int B , int N ) { float d = ( float ) ( B - A ) / ( N + 1 ) ; for ( int i = 1 ; i <= N ; i ++ ) cout << ( A + i * d ) << " β " ; } int main ( ) { int A = 20 , B = 32 , N = 5 ; printAMeans ( A , B , N ) ; return 0 ; } |
Prime Factor | Program to print all prime factors ; A function to print all prime factors of a given number n ; Print the number of 2 s that divide n ; n must be odd at this point . So we can skip one element ( Note i = i + 2 ) ; While i divides n , print i and divide n ; This condition is to handle the case when n is a prime number greater than 2 ; Driver program to test above function | # include <stdio.h> NEW_LINE # include <math.h> NEW_LINE void primeFactors ( int n ) { while ( n % 2 == 0 ) { printf ( " % d β " , 2 ) ; n = n / 2 ; } for ( int i = 3 ; i <= sqrt ( n ) ; i = i + 2 ) { while ( n % i == 0 ) { printf ( " % d β " , i ) ; n = n / i ; } } if ( n > 2 ) printf ( " % d β " , n ) ; } int main ( ) { int n = 315 ; primeFactors ( n ) ; return 0 ; } |
Time taken by two persons to meet on a circular track | C ++ implementation of above approach ; Function to return the time when both the persons will meet at the starting point ; Time to cover 1 round by both ; Finding LCM to get the meeting point ; Function to return the time when both the persons will meet for the first time ; Driver Code ; Calling function | #include <bits/stdc++.h> NEW_LINE using namespace std ; int startingPoint ( int Length , int Speed1 , int Speed2 ) { int result1 = 0 , result2 = 0 ; int time1 = Length / Speed1 ; int time2 = Length / Speed2 ; result1 = __gcd ( time1 , time2 ) ; result2 = time1 * time2 / ( result1 ) ; return result2 ; } float firstTime ( int Length , int Speed1 , int Speed2 ) { float result = 0 ; int relativeSpeed = abs ( Speed1 - Speed2 ) ; result = ( ( float ) Length / relativeSpeed ) ; return result ; } int main ( ) { int L = 30 , S1 = 5 , S2 = 2 ; float first_Time = firstTime ( L , S1 , S2 ) ; int starting_Point = startingPoint ( L , S1 , S2 ) ; cout << " Met β first β time β after β " << first_Time << " β hrs " << endl ; cout << " Met β at β starting β point β after β " << starting_Point << " β hrs " << endl ; 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.