text
stringlengths
17
4.49k
code
stringlengths
49
5.46k
Check if sum of count of digits of array elements is Prime or not | C ++ program for the above approach ; Function to check whether a number is prime or not ; Corner cases ; If given number is a multiple of 2 or 3 ; Function to check if sum of count of digits of all array elements is prime or not ; Initialize sum with 0 ; Traverse over the array ; Convert array element to string ; Add the count of digits to sum ; Print the result ; Drive Code ; Function call
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool isPrime ( int n ) { if ( n <= 1 ) return false ; if ( n <= 3 ) return true ; if ( n % 2 == 0 n % 3 == 0 ) return false ; for ( int i = 5 ; i * i <= n ; i = i + 6 ) if ( n % i == 0 || n % ( i + 2 ) == 0 ) return false ; return true ; } void CheckSumPrime ( int A [ ] , int N ) { int sum = 0 ; for ( int i = 0 ; i < N ; i ++ ) { string s = to_string ( A [ i ] ) ; sum += s . length ( ) ; } if ( isPrime ( sum ) ) { cout << " Yes " << endl ; } else { cout << " No " << endl ; } } int main ( ) { int A [ ] = { 1 , 11 , 12 } ; int N = sizeof ( A ) / sizeof ( A [ 0 ] ) ; CheckSumPrime ( A , N ) ; return 0 ; }
Probability of obtaining Prime Numbers as product of values obtained by throwing N dices | C ++ program to implement the above approach ; Function to find the value of power ( X , N ) ; Stores the value of ( X ^ N ) ; Calculate the value of power ( x , N ) ; If N is odd ; Update res ; Update x ; Update N ; Function to find the probability of obtaining a prime number as the product of N thrown dices ; Stores count of favorable outcomes ; Stores count of sample space ; Print the required probability ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; long long int power ( long long int x , long long int N ) { long long int res = 1 ; while ( N > 0 ) { if ( N & 1 ) { res = ( res * x ) ; } x = ( x * x ) ; N = N >> 1 ; } return res ; } void probablityPrimeprod ( long long int N ) { long long int N_E = 3 * N ; long long int N_S = power ( 6 , N ) ; cout << N_E << " ▁ / ▁ " << N_S ; } int main ( ) { long long int N = 2 ; probablityPrimeprod ( N ) ; }
Smaller palindromic number closest to N | C ++ program to implement the above approach ; Function to check if a number is palindrome or not ; Stores reverse of N ; Stores the value of N ; Calculate reverse of N ; Update rev ; Update N ; Update N ; if N is equal to rev of N ; Function to find the closest smaller palindromic number to N ; Calculate closest smaller palindromic number to N ; Update N ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool checkPalindrome ( int N ) { int rev = 0 ; int temp = N ; while ( N != 0 ) { rev = rev * 10 + N % 10 ; N = N / 10 ; } N = temp ; if ( N == rev ) { return true ; } return false ; } int closestSmallerPalindrome ( int N ) { do { N -- ; } while ( N >= 0 && ! checkPalindrome ( N ) ) ; return N ; } int main ( ) { int N = 4000 ; cout << closestSmallerPalindrome ( N ) ; return 0 ; }
Minimize increments or decrements by 2 to convert given value to a perfect square | C ++ program to implement the above approach ; Function to find the minimum number of operations required to make N a perfect square ; Stores count of operations by performing decrements ; Stores value of N ; Decrement the value of temp ; Stores square root of temp ; If temp is a perfect square ; Update temp ; Store count of operations by performing increments ; Increment the value of N ; Stores sqrt of N ; If N is a perfect square ; Update temp ; Return the minimum count ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int MinimumOperationReq ( int N ) { int cntDecr = 0 ; int temp = N ; while ( temp > 0 ) { int X = sqrt ( temp ) ; if ( X * X == temp ) { break ; } temp = temp - 2 ; cntDecr += 1 ; } int cntIncr = 0 ; while ( true ) { int X = sqrt ( N ) ; if ( X * X == N ) { break ; } N = N + 2 ; cntIncr += 1 ; } return min ( cntIncr , cntDecr ) ; } int main ( ) { int N = 15 ; cout << MinimumOperationReq ( N ) ; return 0 ; }
First term from given Nth term of the equation F ( N ) = ( 2 * F ( N | C ++ program to implement the above approach ; Function to find the value of power ( X , N ) % M ; Stores the value of ( X ^ N ) % M ; Calculate the value of power ( x , N ) % M ; If N is odd ; Update res ; Update x ; Update N ; Function to find modulo multiplicative inverse of X under modulo M ; Function to find the value of F ( 1 ) ; Stores power ( 2 , N - 1 ) ; Stores modulo multiplicative inverse of P_2 under modulo M ; Stores the value of F ( 1 ) ; Update res ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; #define M 1000000007 NEW_LINE long long power ( long long x , long long N ) { long long res = 1 ; while ( N > 0 ) { if ( N & 1 ) { res = ( res * x ) % M ; } x = ( x * x ) % M ; N = N >> 1 ; } return res ; } long long moduloInverse ( long long X ) { return power ( X , M - 2 ) ; } long long F_1 ( long long N , long long F_N ) { long long P_2 = power ( 2 , N - 1 ) ; long long modInv = moduloInverse ( P_2 ) ; long long res ; res = ( ( modInv % M ) * ( F_N % M ) ) % M ; return res ; } int main ( ) { long long N = 3 ; long long F_N = 6 ; cout << F_1 ( N , F_N ) ; }
Queries to replace every array element by its XOR with a given value with updates | C ++ program of the above approach ; Function to insert an element into the array ; Function to update every array element a [ i ] by a [ i ] ^ x ; Function to compute the final results after the operations ; Driver Code ; Queries ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; #define int long long NEW_LINE void add ( vector < int > & arr , int x ) { arr . push_back ( x ) ; } void update ( int & effect , int x ) { effect = effect ^ x ; } void computeResults ( vector < int > & arr , int effect ) { for ( int i = 0 ; i < arr . size ( ) ; i ++ ) { arr [ i ] = arr [ i ] ^ effect ; cout << arr [ i ] << " ▁ " ; } } signed main ( ) { vector < int > arr = { 0 } ; int effect = 0 ; add ( arr , 5 ) ; update ( effect , 2 ) ; computeResults ( arr , effect ) ; }
Check if a subarray of size K exists whose elements form a number divisible by 3 | C ++ implementation of the above approach ; Function to find the K size subarray ; Check if the first K elements forms a number which is divisible by 3 ; Using Sliding window technique ; Calculate sum of next K size subarray ; Check if sum is divisible by 3 ; Update the indices of the subarray ; If no such subarray is found ; Print the subarray ; Driver 's code ; Given array and K ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; void findSubArray ( vector < int > arr , int k ) { pair < int , int > ans ; int i , sum = 0 ; for ( i = 0 ; i < k ; i ++ ) { sum += arr [ i ] ; } int found = 0 ; if ( sum % 3 == 0 ) { ans = make_pair ( 0 , i - 1 ) ; found = 1 ; } for ( int j = i ; j < arr . size ( ) ; j ++ ) { if ( found == 1 ) break ; sum = sum + arr [ j ] - arr [ j - k ] ; if ( sum % 3 == 0 ) { ans = make_pair ( j - k + 1 , j ) ; found = 1 ; } } if ( found == 0 ) ans = make_pair ( -1 , 0 ) ; if ( ans . first == -1 ) { cout << -1 ; } else { for ( i = ans . first ; i <= ans . second ; i ++ ) { cout << arr [ i ] << " ▁ " ; } } } int main ( ) { vector < int > arr = { 84 , 23 , 45 , 12 , 56 , 82 } ; int K = 3 ; findSubArray ( arr , K ) ; return 0 ; }
Count permutations of given array that generates the same Binary Search Tree ( BST ) | C ++ program to implement the above approach ; Function to precompute the factorial of 1 to N ; Function to get the value of nCr ; nCr = fact ( n ) / ( fact ( r ) * fact ( n - r ) ) ; Function to count the number of ways to rearrange the array to obtain same BST ; Store the size of the array ; Base case ; Store the elements of the left subtree of BST ; Store the elements of the right subtree of BST ; Store the root node ; Push all the elements of the left subtree ; Push all the elements of the right subtree ; Store the size of leftSubTree ; Store the size of rightSubTree ; Recurrence relation ; Driver Code ; Store the size of arr ; Store the factorial up to N ; Precompute the factorial up to N
#include <bits/stdc++.h> NEW_LINE using namespace std ; void calculateFact ( int fact [ ] , int N ) { fact [ 0 ] = 1 ; for ( long long int i = 1 ; i < N ; i ++ ) { fact [ i ] = fact [ i - 1 ] * i ; } } int nCr ( int fact [ ] , int N , int R ) { if ( R > N ) return 0 ; int res = fact [ N ] / fact [ R ] ; res /= fact [ N - R ] ; return res ; } int countWays ( vector < int > & arr , int fact [ ] ) { int N = arr . size ( ) ; if ( N <= 2 ) { return 1 ; } vector < int > leftSubTree ; vector < int > rightSubTree ; int root = arr [ 0 ] ; for ( int i = 1 ; i < N ; i ++ ) { if ( arr [ i ] < root ) { leftSubTree . push_back ( arr [ i ] ) ; } else { rightSubTree . push_back ( arr [ i ] ) ; } } int N1 = leftSubTree . size ( ) ; int N2 = rightSubTree . size ( ) ; int countLeft = countWays ( leftSubTree , fact ) ; int countRight = countWays ( rightSubTree , fact ) ; return nCr ( fact , N - 1 , N1 ) * countLeft * countRight ; } int main ( ) { vector < int > arr ; arr = { 3 , 4 , 5 , 1 , 2 } ; int N = arr . size ( ) ; int fact [ N ] ; calculateFact ( fact , N ) ; cout << countWays ( arr , fact ) ; return 0 ; }
Sum of all ordered pair | C ++ program to implement the above approach ; Function to calculate the sum of all pair - products ; Stores sum of array ; Update sum of the array ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int sumOfProd ( int arr [ ] , int N ) { int sum = 0 ; for ( int i = 0 ; i < N ; i ++ ) { sum += arr [ i ] ; } return sum * sum ; } int main ( ) { int arr [ ] = { 2 , 3 , 1 , 5 , 4 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << sumOfProd ( arr , N ) ; return 0 ; }
Check if a given number is one less than twice its reverse | C ++ program of the above approach ; Iterative function to reverse digits of num ; Loop to extract all digits of the number ; Function to check if N satisfies given equation ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int rev ( int num ) { int rev_num = 0 ; while ( num > 0 ) { rev_num = rev_num * 10 + num % 10 ; num = num / 10 ; } return rev_num ; } bool check ( int n ) { return 2 * rev ( n ) == n + 1 ; } int main ( ) { int n = 73 ; if ( check ( n ) ) cout << " Yes " ; else cout << " No " ; return 0 ; }
Check if a given number is one less than twice its reverse | C ++ program to implement the above approach ; Function to check y is a power of x ; logarithm function to calculate value ; Compare to the result1 or result2 both are equal ; Function to check if N satisfies the equation 2 * reverse ( n ) = n + 1 ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool isPower ( int x , int y ) { int res1 = log ( y ) / log ( x ) ; double res2 = log ( y ) / log ( x ) ; return ( res1 == res2 ) ; } bool check ( int n ) { int x = ( n + 7 ) / 8 ; if ( ( n + 7 ) % 8 == 0 && isPower ( 10 , x ) ) return true ; else return false ; } int main ( ) { int n = 73 ; if ( check ( n ) ) cout << " Yes " ; else cout << " No " ; return 0 ; }
Nth term of a recurrence relation generated by two given arrays | C ++ program for the above approach ; Function to calculate Nth term of general recurrence relations ; Stores the generated sequence ; Current term is sum of previous k terms ; Print the nth term ; Driver Code ; Given Array F [ ] and C [ ] ; Given N and K ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; int mod = 1e9 + 7 ; void NthTerm ( int F [ ] , int C [ ] , int K , int n ) { int ans [ n + 1 ] = { 0 } ; for ( int i = 0 ; i < K ; i ++ ) ans [ i ] = F [ i ] ; for ( int i = K ; i <= n ; i ++ ) { for ( int j = i - K ; j < i ; j ++ ) { ans [ i ] += ans [ j ] ; ans [ i ] %= mod ; } } cout << ans [ n ] << endl ; } int main ( ) { int F [ ] = { 0 , 1 } ; int C [ ] = { 1 , 1 } ; int K = 2 ; int N = 10 ; NthTerm ( F , C , K , N ) ; return 0 ; }
Mode of frequencies of given array elements | C ++ program of the above approach ; Function to find the mode of the frequency of the array ; Stores the frequencies of array elements ; Traverse through array elements and count frequencies ; Stores the frequencies 's of frequencies of array elements ; Stores the minimum value ; Find the Mode in 2 nd map ; search for this Mode ; When mode is find then return to main function . ; If mode is not found ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int countFreq ( int arr [ ] , int n ) { unordered_map < int , int > mp1 ; for ( int i = 0 ; i < n ; ++ i ) { mp1 [ arr [ i ] ] ++ ; } unordered_map < int , int > mp2 ; for ( auto it : mp1 ) { mp2 [ it . second ] ++ ; } int M = INT_MIN ; for ( auto it : mp2 ) { M = max ( M , it . second ) ; } for ( auto it : mp2 ) { if ( M == it . second ) { return it . first ; } } return 0 ; } int main ( ) { int arr [ ] = { 6 , 10 , 3 , 10 , 8 , 3 , 6 , 4 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << countFreq ( arr , n ) ; return 0 ; }
Maximize count of nodes disconnected from all other nodes in a Graph | C ++ implementation of the above approach ; Function which returns the maximum number of isolated nodes ; Used nodes ; Remaining edges ; Count nodes used ; If given edges are non - zero ; Driver Code ; Given N and E ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; int maxDisconnected ( int N , int E ) { int curr = 1 ; int rem = E ; while ( rem > 0 ) { rem = rem - min ( curr , rem ) ; curr ++ ; } if ( curr > 1 ) { return N - curr ; } else { return N ; } } int main ( ) { int N = 5 , E = 1 ; cout << maxDisconnected ( N , E ) ; return 0 ; }
Check if number is palindrome or not in base B | C ++ program to implement the above approach ; Function to check if N in base B is palindrome or not ; Stores the reverse of N ; Stores the value of N ; Extract all the digits of N ; Generate its reverse ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int checkPalindromeB ( int N , int B ) { int rev = 0 ; int N1 = N ; while ( N1 ) { rev = rev * B + N1 % B ; N1 = N1 / B ; } return N == rev ; } int main ( ) { int N = 5 , B = 2 ; if ( checkPalindromeB ( N , B ) ) { cout << " Yes " ; } else { cout << " No " ; } }
Product of all numbers up to N that are co | C ++ program for the above approach ; Function to return gcd of a and b ; Base Case ; Recursive GCD ; Function to find the product of all the numbers till N that are relatively prime to N ; Stores the resultant product ; Iterate over [ 2 , N ] ; If gcd is 1 , then find the product with result ; Return the final product ; Driver Code
#include <iostream> NEW_LINE using namespace std ; int gcd ( int a , int b ) { if ( a == 0 ) return b ; return gcd ( b % a , a ) ; } int findProduct ( unsigned int N ) { unsigned int result = 1 ; for ( int i = 2 ; i < N ; i ++ ) { if ( gcd ( i , N ) == 1 ) { result *= i ; } } return result ; } int main ( ) { int N = 5 ; cout << findProduct ( N ) ; return 0 ; }
Maximize count of equal numbers in Array of numbers upto N by replacing pairs with their sum | C ++ implementation of the above approach ; Function to count maximum number of array elements equal ; Driver Code ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; int countEqual ( int n ) { return ( n + 1 ) / 2 ; } int main ( ) { int arr [ ] = { 1 , 2 , 3 , 4 , 5 , 6 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << countEqual ( n ) ; return 0 ; }
Minimize count of unequal elements at corresponding indices between given arrays | C ++ program for the above approach ; Function that count of the mismatched pairs in bot the array ; Create a parent array and initialize it ; Preprocessing of the given pairs of indices ; 1 - based indexing ; If both indices doesn 't belong to same component ; Insert the indices in same component ; Map to get the indices of array A ; If current element is not present in array B then count this as mismatched ; Get the index of the element in array B ; Check if both indices belong to same connected component if not increment the count ; Return answer ; Function that gives the connected component of each index ; Function that creates the connected components ; Find parent of a and b recursively ; Update the parent of a ; Driver Code ; Given arrays A [ ] , B [ ] ; List of indices ; Function call
#include <bits/stdc++.h> NEW_LINE using namespace std ; int find ( int par [ ] , int x ) ; void unionn ( int par [ ] , int a , int b ) ; int countPairs ( int A [ ] , int B [ ] , int N , int M , int List [ ] [ 2 ] ) { int count = 0 ; int par [ N + 1 ] ; for ( int i = 0 ; i <= N ; i ++ ) par [ i ] = i ; for ( int i = 0 ; i < M ; i ++ ) { int index1 = find ( par , List [ i ] [ 0 ] - 1 ) ; int index2 = find ( par , List [ i ] [ 1 ] - 1 ) ; if ( index1 != index2 ) { unionn ( par , index1 , index2 ) ; } } map < int , int > mp ; for ( int i = 0 ; i < N ; i ++ ) { mp [ A [ i ] ] = i ; } for ( int i = 0 ; i < N ; i ++ ) { if ( A [ i ] != B [ i ] ) { if ( mp . find ( B [ i ] ) == mp . end ( ) ) { count ++ ; continue ; } int j = mp [ B [ i ] ] ; if ( find ( par , i ) != find ( par , j ) ) count ++ ; } } return count ; } int find ( int par [ ] , int x ) { if ( par [ x ] == x ) return x ; else return par [ x ] = find ( par , par [ x ] ) ; } void unionn ( int par [ ] , int a , int b ) { a = find ( par , a ) ; b = find ( par , b ) ; if ( a == b ) return ; par [ a ] = b ; } int main ( ) { int N = 5 ; int M = 4 ; int A [ ] = { 1 , 5 , 9 , 2 , 3 } ; int B [ ] = { 2 , 4 , 5 , 1 , 3 } ; int List [ ] [ 2 ] = { { 1 , 4 } , { 2 , 3 } , { 3 , 5 } , { 2 , 5 } } ; cout << countPairs ( A , B , N , M , List ) ; return 0 ; }
Maximum value of expression ( arr [ i ] + arr [ j ] * arr [ k ] ) formed from a valid Triplet | C ++ program for the above approach ; Function that generate all valid triplets and calculate the value of the valid triplets ; Generate all triplets ; Check whether the triplet is valid or not ; Update the value ; Print the maximum value ; Driver Code ; Given array arr [ ] ; Function call
#include <bits/stdc++.h> NEW_LINE using namespace std ; void max_valid_triplet ( int A [ ] , int n ) { int ans = -1 ; for ( int i = 0 ; i < n - 2 ; i ++ ) { for ( int j = i + 1 ; j < n - 1 ; j ++ ) { for ( int k = j + 1 ; k < n ; k ++ ) { if ( A [ i ] < A [ j ] && A [ j ] < A [ k ] ) { int value = A [ i ] + A [ j ] * A [ k ] ; if ( value > ans ) { ans = value ; } } } } } cout << ( ans ) ; } int main ( ) { int arr [ ] = { 7 , 9 , 3 , 8 , 11 , 10 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; max_valid_triplet ( arr , n ) ; return 0 ; }
Product of proper divisors of a number for Q queries | C ++ implementation of the above approach ; Function to precompute the product of proper divisors of a number at it 's corresponding index ; Returning the pre - computed values ; Driver code
#include <bits/stdc++.h> NEW_LINE #define ll long long int NEW_LINE #define mod 1000000007 NEW_LINE using namespace std ; vector < ll > ans ( 100002 , 1 ) ; void preCompute ( ) { for ( int i = 2 ; i <= 100000 / 2 ; i ++ ) { for ( int j = 2 * i ; j <= 100000 ; j += i ) { ans [ j ] = ( ans [ j ] * i ) % mod ; } } } int productOfProperDivi ( int num ) { return ans [ num ] ; } int main ( ) { preCompute ( ) ; int queries = 5 ; int a [ queries ] = { 4 , 6 , 8 , 16 , 36 } ; for ( int i = 0 ; i < queries ; i ++ ) { cout << productOfProperDivi ( a [ i ] ) << " , ▁ " ; } return 0 ; }
Highest power of 2 that divides the LCM of first N Natural numbers . | C ++ implementation of the approach ; Function to find LCM of first N natural numbers ; Initialize result ; Ans contains LCM of 1 , 2 , 3 , . . i after i 'th iteration ; Function to find the highest power of 2 which divides LCM of first n natural numbers ; Find lcm of first N natural numbers ; To store the highest required power of 2 ; Counting number of consecutive zeros from the end in the given binary string ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int findlcm ( int n ) { int ans = 1 ; for ( int i = 1 ; i <= n ; i ++ ) ans = ( ( ( i * ans ) ) / ( __gcd ( i , ans ) ) ) ; return ans ; } int highestPower ( int n ) { int lcm = findlcm ( n ) ; int ans = 0 ; for ( int i = 1 ; ; i ++ ) { int x = pow ( 2 , i ) ; if ( lcm % x == 0 ) { ans = i ; } if ( x > n ) break ; } return ans ; } int main ( ) { int n = 15 ; cout << highestPower ( n ) ; return 0 ; }
Highest power of 2 that divides the LCM of first N Natural numbers . | C ++ implementation of the approach ; Function to find the highest power of 2 which divides LCM of first n natural numbers ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int highestPower ( int n ) { return log ( n ) / log ( 2 ) ; } int main ( ) { int n = 15 ; cout << highestPower ( n ) ; return 0 ; }
Check if number can be made prime by deleting a single digit | C ++ implementation to check if a number becomes prime by deleting any digit ; Function to check if N is prime ; Corner cases ; This is checked so that we can skip middle five numbers in below loop ; Function to delete character at index i from given string str ; Deletes character at position 4 ; Function to check if a number becomes prime by deleting any digit ; Converting the number to string ; length of string ; number should not be of single digit ; Loop to find all numbers after deleting a single digit ; Deleting ith character from the string ; converting string to int ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool isPrime ( int n ) { if ( n <= 1 ) return false ; if ( n <= 3 ) return true ; if ( n % 2 == 0 n % 3 == 0 ) return false ; for ( int i = 5 ; i * i <= n ; i = i + 6 ) if ( n % i == 0 || n % ( i + 2 ) == 0 ) return false ; return true ; } string deleteIth ( string str , int i ) { str . erase ( str . begin ( ) + i ) ; return str ; } bool isPrimePossible ( int N ) { string s = to_string ( N ) ; int l = s . length ( ) ; if ( l < 2 ) return false ; for ( int i = 0 ; i < l ; i ++ ) { string str = deleteIth ( s , i ) ; int num = stoi ( str ) ; if ( isPrime ( num ) ) return true ; } return false ; } int main ( ) { int N = 610 ; isPrimePossible ( N ) ? cout << " Yes " : cout << " No " ; return 0 ; }
Check if a number has an odd count of odd divisors and even count of even divisors | C ++ implementation of the above approach ; Function to find the count of even and odd factors of N ; Loop runs till square root ; Condition to check if the even factors of the number N is is even and count of odd factors is odd ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; #define lli long long int NEW_LINE void checkFactors ( lli N ) { lli ev_count = 0 , od_count = 0 ; for ( lli i = 1 ; i <= sqrt ( N ) + 1 ; i ++ ) { if ( N % i == 0 ) { if ( i == N / i ) { if ( i % 2 == 0 ) ev_count += 1 ; else od_count += 1 ; } else { if ( i % 2 == 0 ) ev_count += 1 ; else od_count += 1 ; if ( ( N / i ) % 2 == 0 ) ev_count += 1 ; else od_count += 1 ; } } } if ( ev_count % 2 == 0 && od_count % 2 == 1 ) cout << " Yes " << endl ; else cout << " No " << endl ; } int main ( ) { lli N = 36 ; checkFactors ( N ) ; return 0 ; }
Count of distinct permutations of length N having no similar adjacent characters | C ++ Program to implement the above approach ; Function to print the number of permutations possible ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int countofPermutations ( int N ) { return int ( 3 * pow ( 2 , N - 1 ) ) ; } int main ( ) { int N = 5 ; cout << countofPermutations ( N ) ; return 0 ; }
Find two distinct numbers such that their LCM lies in given range | C ++ program for the above approach ; Function to find two distinct numbers X and Y s . t . their LCM lies between L and R and X , Y are minimum possible ; Check if 2 * L lies in range L , R ; Print the answer ; Driver Code ; Given value of ranges ; Function call
#include <bits/stdc++.h> NEW_LINE using namespace std ; void answer ( int L , int R ) { if ( 2 * L <= R ) cout << L << " , ▁ " << 2 * L << " STRNEWLINE " ; else cout << -1 ; } int main ( ) { int L = 3 , R = 8 ; answer ( L , R ) ; return 0 ; }
Maximum count of pairwise co | C ++ program for the above approach ; Function to find the gcd of two numbers ; Function to of pairwise co - prime and common divisors of two numbers ; Initialize answer with 1 , to include 1 in the count ; Count of primes of gcd ( N , M ) ; Finding prime factors of gcd ; Increment count if it is divisible by i ; Return the total count ; Function Call for each pair to calculate the count of pairwise co - prime divisors ; Driver Code ; Given array of pairs ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; int gcd ( int x , int y ) { if ( x % y == 0 ) return y ; else return gcd ( y , x % y ) ; } int countPairwiseCoprime ( int N , int M ) { int answer = 1 ; int g = gcd ( N , M ) ; int temp = g ; for ( int i = 2 ; i * i <= g ; i ++ ) { if ( temp % i == 0 ) { answer ++ ; while ( temp % i == 0 ) temp /= i ; } } if ( temp != 1 ) answer ++ ; return answer ; } void countCoprimePair ( int arr [ ] [ 2 ] , int N ) { for ( int i = 0 ; i < N ; i ++ ) { cout << countPairwiseCoprime ( arr [ i ] [ 0 ] , arr [ i ] [ 1 ] ) << ' ▁ ' ; } } int main ( ) { int arr [ ] [ 2 ] = { { 12 , 18 } , { 420 , 660 } } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; countCoprimePair ( arr , N ) ; return 0 ; }
Product of absolute difference of every pair in given Array | C ++ program for the above approach ; Function to return the product of abs diff of all pairs ( x , y ) ; To store product ; Iterate all possible pairs ; Find the product ; Return product ; Driver Code ; Given array arr [ ] ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; int getProduct ( int a [ ] , int n ) { int p = 1 ; for ( int i = 0 ; i < n ; i ++ ) { for ( int j = i + 1 ; j < n ; j ++ ) { p *= abs ( a [ i ] - a [ j ] ) ; } } return p ; } int main ( ) { int arr [ ] = { 1 , 2 , 3 , 4 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << getProduct ( arr , N ) ; return 0 ; }
Check whether a number can be represented as difference of two consecutive cubes | C ++ program for the above approach ; Function to print the two consecutive numbers whose difference is N ; Iterate in the range [ 0 , 10 ^ 5 ] ; Function to check if N is a perfect cube ; Find floating point value of square root of x . ; If square root is an integer ; Function to check whether a number can be represented as difference of two consecutive cubes ; Check if 12 * N - 3 is a perfect square or not ; Driver Code ; Given Number N
#include <bits/stdc++.h> NEW_LINE using namespace std ; void print ( int N ) { for ( int i = 0 ; i < 100000 ; i ++ ) { if ( pow ( i + 1 , 3 ) - pow ( i , 3 ) == N ) { cout << i << ' ▁ ' << i + 1 ; return ; } } } bool isPerfectSquare ( long double x ) { long double sr = sqrt ( x ) ; return ( ( sr - floor ( sr ) ) == 0 ) ; } bool diffCube ( int N ) { return isPerfectSquare ( 12 * N - 3 ) ; } int main ( ) { int N = 19 ; if ( diffCube ( N ) ) { cout << " Yes STRNEWLINE " ; print ( N ) ; } else { cout << " No STRNEWLINE " ; } return 0 ; }
Sum of bit differences for numbers from 0 to N | Set 2 | C ++ program to find the sum of bit differences between consecutive numbers from 0 to N using recursion ; Recursive function to find sum of different bits between consecutive numbers from 0 to N ; Base case ; Calculate the Nth term ; Driver Code ; Given Number ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; int totalCountDifference ( int n ) { if ( n == 1 ) return 1 ; return n + totalCountDifference ( n / 2 ) ; } int main ( ) { int N = 5 ; cout << totalCountDifference ( N ) ; return 0 ; }
Sum of elements of a Geometric Progression ( GP ) in a given range | C ++ program to find the sum of elements of an GP in the given range ; Function to find sum in the given range ; Find the value of k ; Find the common difference ; Find the sum ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int findSum ( int arr [ ] , int n , int left , int right ) { int k = right - left + 1 ; int d = arr [ 1 ] / arr [ 0 ] ; int ans = arr [ left - 1 ] ; if ( d == 1 ) ans = ans * d * k ; else ans = ans * ( ( int ) pow ( d , k ) - 1 / ( d - 1 ) ) ; return ans ; } int main ( ) { int arr [ ] = { 2 , 4 , 8 , 16 , 32 , 64 , 128 , 256 } ; int queries = 3 ; int q [ ] [ 2 ] = { { 2 , 4 } , { 2 , 6 } , { 5 , 8 } } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; for ( int i = 0 ; i < queries ; i ++ ) cout << ( findSum ( arr , n , q [ i ] [ 0 ] , q [ i ] [ 1 ] ) ) << endl ; return 0 ; }
Find the first and last M digits from K | C ++ Program to implement the above approach ; Function to find a ^ b modulo M ; Function to find the first and last M digits from N ^ K ; Calculate Last M digits ; Calculate First M digits ; Extract the number after decimal ; Find 10 ^ y ; Move the Decimal Point M - 1 digits forward ; Print the result ; Driver Code
#include <bits/stdc++.h> NEW_LINE #define ll long long int NEW_LINE using namespace std ; ll modPower ( ll a , ll b , ll M ) { ll res = 1 ; while ( b ) { if ( b & 1 ) res = res * a % M ; a = a * a % M ; b >>= 1 ; } return res ; } void findFirstAndLastM ( ll N , ll K , ll M ) { ll lastM = modPower ( N , K , ( 1LL ) * pow ( 10 , M ) ) ; ll firstM ; double y = ( double ) K * log10 ( N * 1.0 ) ; y = y - ( ll ) y ; double temp = pow ( 10.0 , y ) ; firstM = temp * ( 1LL ) * pow ( 10 , M - 1 ) ; cout << firstM << " ▁ " << lastM << endl ; } int main ( ) { ll N = 12 , K = 12 , M = 4 ; findFirstAndLastM ( N , K , M ) ; return 0 ; }
Minimize increment / decrement of Array elements to make each modulo K equal | C ++ program for the above approach ; Function to find the minimum operations required to make the modulo of each element of the array equal to each other ; Variable to store minimum operation required ; To store operation required to make all modulo equal ; Iterating through all possible modulo value ; Iterating through all different modulo obtained so far ; Calculating oprn required to make all modulos equal to x ; Checking the operations that will cost less ; Check operation that will cost less ; Update the minimum number of operations ; Returning the answer ; Function to store different modulos ; Set to store all different modulo ; Map to store count of all different modulo obtained ; Storing all different modulo count ; Insert into the set ; Increment count ; Function call to return value of min oprn required ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int Find_min ( set < int > & diff_mod , map < int , int > count_mod , int k ) { int min_oprn = INT_MAX ; int oprn = 0 ; for ( int x = 0 ; x < k ; x ++ ) { oprn = 0 ; for ( auto w : diff_mod ) { if ( w != x ) { if ( w == 0 ) { oprn += min ( x , k - x ) * count_mod [ w ] ; } else { oprn += min ( abs ( x - w ) , k + x - w ) * count_mod [ w ] ; } } } if ( oprn < min_oprn ) min_oprn = oprn ; } return min_oprn ; } int Cal_min ( int arr [ ] , int n , int k ) { set < int > diff_mod ; map < int , int > count_mod ; for ( int i = 0 ; i < n ; i ++ ) { diff_mod . insert ( arr [ i ] % k ) ; count_mod [ arr [ i ] % k ] ++ ; } return Find_min ( diff_mod , count_mod , k ) ; } int main ( ) { int arr [ ] = { 2 , 35 , 48 , 23 , 52 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; int k = 3 ; cout << Cal_min ( arr , n , k ) ; return 0 ; }
Minimize Steps required to obtain Sorted Order of an Array | C ++ Program to implement the above approach ; Function to find GCD of two numbers ; Function to calculate the LCM of array elements ; Initialize result ; Function to find minimum steps required to obtain sorted sequence ; Inititalize dat [ ] array for Direct Address Table . ; Calculating steps required for each element to reach its sorted position ; Calculate LCM of the array ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int gcd ( int a , int b ) { if ( b == 0 ) return a ; return gcd ( b , a % b ) ; } int findlcm ( int arr [ ] , int n ) { int ans = 1 ; for ( int i = 1 ; i <= n ; i ++ ) ans = ( ( ( arr [ i ] * ans ) ) / ( gcd ( arr [ i ] , ans ) ) ) ; return ans ; } void minimumSteps ( int arr [ ] , int n ) { int i , dat [ n + 1 ] ; for ( i = 1 ; i <= n ; i ++ ) dat [ arr [ i - 1 ] ] = i ; int b [ n + 1 ] , j = 0 , c ; for ( i = 1 ; i <= n ; i ++ ) { c = 1 ; j = dat [ i ] ; while ( j != i ) { c ++ ; j = dat [ j ] ; } b [ i ] = c ; } cout << findlcm ( b , n ) ; } int main ( ) { int arr [ ] = { 5 , 1 , 4 , 3 , 2 , 7 , 6 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; minimumSteps ( arr , N ) ; return 0 ; }
Largest Ratio Contiguous subarray | C ++ program for the above approach ; Function to return maximum of two double values ; Check if a is greater than b then return a ; Function that returns the Ratio of max Ratio subarray ; Variable to store the maximum ratio ; Compute the product while traversing for subarrays ; Calculate the ratio ; Update max ratio ; Print the answer ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; double maximum ( double a , double b ) { if ( a > b ) return a ; return b ; } double maxSubarrayRatio ( double arr [ ] , int n ) { double maxRatio = INT_MIN ; for ( int i = 0 ; i < n ; i ++ ) { for ( int j = i ; j < n ; j ++ ) { double ratio = arr [ i ] ; for ( int k = i + 1 ; k <= j ; k ++ ) { ratio = ratio / arr [ k ] ; } maxRatio = maximum ( maxRatio , ratio ) ; } } return maxRatio ; } int main ( ) { double arr [ ] = { 2 , 2 , 4 , -0.2 , -1 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << maxSubarrayRatio ( arr , n ) ; return 0 ; }
Even Perfect Number | C ++ program for the above approach ; Function to check for perfect number ; Find a number close to 2 ^ q - 1 ; Calculate q - 1 ; Condition of perfect number ; Check whether q is prime or not ; Check whether 2 ^ q - 1 is a prime number or not ; Function to check for prime number ; Check whether it is equal to 2 or 3 ; Check if it can be divided by 2 and 3 then it is not prime number ; Check whether the given number be divide by other prime numbers ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool isPrime ( long n ) ; void check ( long num ) { long root = ( long ) sqrt ( num ) ; long poww = ( long ) ( log ( root ) / log ( 2 ) ) ; if ( num == ( long ) ( pow ( 2 , poww ) * ( pow ( 2 , poww + 1 ) - 1 ) ) ) { if ( isPrime ( poww + 1 ) ) { if ( isPrime ( ( long ) pow ( 2 , poww + 1 ) - 1 ) ) cout << " Yes " << endl ; else cout << " No " << endl ; } else cout << " No " << endl ; } else cout << " No " << endl ; } bool isPrime ( long n ) { if ( n <= 1 ) return false ; else if ( n == 2 n == 3 ) return true ; else { if ( n % 2 == 0 n % 3 == 0 ) return false ; for ( long i = 5 ; i <= sqrt ( n ) ; i += 6 ) { if ( n % i == 0 || n % ( i + 2 ) == 0 ) return false ; } return true ; } } int main ( ) { long num = 6 ; check ( num ) ; return 0 ; }
Twin Pythagorean triplets in an array | C ++ program for the above approach ; Function to check if there exist a twin pythagorean triplet in the given array ; Loop to check if there is a Pythagorean triplet in the array ; Check if there is consecutive triple ; Calculate square of array elements ; Driver Code ; Given array arr [ ] ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool isTriplet ( int ar [ ] , int n ) { for ( int i = 0 ; i < n ; i ++ ) { for ( int j = i + 1 ; j < n ; j ++ ) { for ( int k = j + 1 ; k < n ; k ++ ) { if ( abs ( ar [ i ] - ar [ j ] ) == 1 || abs ( ar [ j ] - ar [ k ] ) == 1 || abs ( ar [ i ] - ar [ k ] ) == 1 ) { int x = ar [ i ] * ar [ i ] , y = ar [ j ] * ar [ j ] , z = ar [ k ] * ar [ k ] ; if ( x == y + z y == x + z z == x + y ) return true ; } } } } return false ; } int main ( ) { int arr [ ] = { 3 , 1 , 4 , 6 , 5 } ; int ar_size = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; isTriplet ( arr , ar_size ) ? cout << " Yes " : cout << " No " ; return 0 ; }
Pair with min absolute difference and whose product is N + 1 or N + 2 | C ++ program for the above approach ; Function to print pair ( a , b ) such that a * b = N + 1 or N + 2 ; Loop to iterate over the desired possible values ; Check for condition 1 ; Check for condition 2 ; Driver Code ; Given Number ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; void closestDivisors ( int n ) { for ( int i = sqrt ( n + 2 ) ; i > 0 ; i -- ) { if ( ( n + 1 ) % i == 0 ) { cout << i << " , ▁ " << ( n + 1 ) / i ; break ; } if ( ( n + 2 ) % i == 0 ) { cout << i << " , ▁ " << ( n + 2 ) / i ; break ; } } } int main ( ) { int N = 123 ; closestDivisors ( N ) ; }
Is it possible to reach N and M from 1 and 0 respectively as per given condition | C ++ program for the above approach ; Function that find given x and y is possible or not ; Check if x is less than 2 and y is not equal to 0 ; Perform subtraction ; Check if y is divisible by 2 and greater than equal to 0 ; Driver Code ; Given X and Y ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool is_possible ( int x , int y ) { if ( x < 2 && y != 0 ) return false ; y = y - x + 1 ; if ( y % 2 == 0 && y >= 0 ) return true ; else return false ; } int main ( ) { int x = 5 , y = 2 ; if ( is_possible ( x , y ) ) cout << " Yes " ; else cout << " No " ; return 0 ; }
Count of integers up to N which are non divisors and non coprime with N | C ++ Program to implement the above approach ; Function to return the count of integers less than N satisfying given conditions ; Stores Euler counts ; Store Divisor counts ; Based on Sieve of Eratosthenes ; Update phi values of all multiples of i ; Update count of divisors ; Return the final count ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int count ( int n ) { int phi [ n + 1 ] = { 0 } ; int divs [ n + 1 ] = { 0 } ; for ( int i = 1 ; i <= n ; i ++ ) { phi [ i ] += i ; for ( int j = i * 2 ; j <= n ; j += i ) phi [ j ] -= phi [ i ] ; for ( int j = i ; j <= n ; j += i ) divs [ j ] ++ ; } return ( n - phi [ n ] - divs [ n ] + 1 ) ; } int main ( ) { int N = 42 ; cout << count ( N ) ; return 0 ; }
Sum of all differences between Maximum and Minimum of increasing Subarrays | C ++ Program to find the sum of differences of maximum and minimum of strictly increasing subarrays ; Function to calculate and return the sum of differences of maximum and minimum of strictly increasing subarrays ; Stores the sum ; Traverse the array ; If last element of the increasing sub - array is found ; Update sum ; If the last element of the array is reached ; Update sum ; Return the sum ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int sum_of_differences ( int arr [ ] , int N ) { int sum = 0 ; int i , j , flag ; for ( i = 0 ; i < N - 1 ; i ++ ) { if ( arr [ i ] < arr [ i + 1 ] ) { flag = 0 ; for ( j = i + 1 ; j < N - 1 ; j ++ ) { if ( arr [ j ] >= arr [ j + 1 ] ) { sum += ( arr [ j ] - arr [ i ] ) ; i = j ; flag = 1 ; break ; } } if ( flag == 0 && arr [ i ] < arr [ N - 1 ] ) { sum += ( arr [ N - 1 ] - arr [ i ] ) ; break ; } } } return sum ; } int main ( ) { int arr [ ] = { 6 , 1 , 2 , 5 , 3 , 4 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << sum_of_differences ( arr , N ) ; return 0 ; }
Construct a Maximum Binary Tree from two given Binary Trees | C ++ program to find the Maximum Binary Tree from two Binary Trees ; A binary tree node has data , pointer to left child and a pointer to right child ; Helper method that allocates a new node with the given data and NULL left and right pointers . ; Given a binary tree , print its nodes in inorder ; First recur on left child ; Then print the data of node ; Now recur on right child ; Method to find the maximum binary tree from two binary trees ; Driver Code ; First Binary Tree 3 / \ 2 6 / 20 ; Second Binary Tree 5 / \ 1 8 \ \ 2 8
#include <bits/stdc++.h> NEW_LINE using namespace std ; class Node { public : int data ; Node * left , * right ; Node ( int data , Node * left , Node * right ) { this -> data = data ; this -> left = left ; this -> right = right ; } } ; Node * newNode ( int data ) { Node * tmp = new Node ( data , NULL , NULL ) ; return tmp ; } void inorder ( Node * node ) { if ( node == NULL ) return ; inorder ( node -> left ) ; cout << node -> data << " ▁ " ; inorder ( node -> right ) ; } Node * MaximumBinaryTree ( Node * t1 , Node * t2 ) { if ( t1 == NULL ) return t2 ; if ( t2 == NULL ) return t1 ; t1 -> data = max ( t1 -> data , t2 -> data ) ; t1 -> left = MaximumBinaryTree ( t1 -> left , t2 -> left ) ; t1 -> right = MaximumBinaryTree ( t1 -> right , t2 -> right ) ; return t1 ; } int main ( ) { Node * root1 = newNode ( 3 ) ; root1 -> left = newNode ( 2 ) ; root1 -> right = newNode ( 6 ) ; root1 -> left -> left = newNode ( 20 ) ; Node * root2 = newNode ( 5 ) ; root2 -> left = newNode ( 1 ) ; root2 -> right = newNode ( 8 ) ; root2 -> left -> right = newNode ( 2 ) ; root2 -> right -> right = newNode ( 8 ) ; Node * root3 = MaximumBinaryTree ( root1 , root2 ) ; inorder ( root3 ) ; }
Minimum size binary string required such that probability of deleting two 1 's at random is 1/X | C ++ implementation of the above approach ; Function returns the minimum size of the string ; From formula ; Left limit of r ; Right limit of r ; Smallest integer in the valid range ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int MinimumString ( int x ) { int b = 1 ; double left_lim = sqrt ( x ) + 1.0 ; double right_lim = sqrt ( x ) + 2.0 ; int r ; for ( int i = left_lim ; i <= right_lim ; i ++ ) { if ( i > left_lim and i < right_lim ) { r = i ; break ; } } return b + r ; } int main ( ) { int X = 2 ; cout << MinimumString ( X ) ; return 0 ; }
Minimum number of squares whose sum equals to a given number N | Set | C ++ program for the above approach ; Function that returns true if N is a perfect square ; Function that returns true check if N is sum of three squares ; Factor out the powers of 4 ; N is NOT of the form 4 ^ a * ( 8 b + 7 ) ; Function that finds the minimum number of square whose sum is N ; If N is perfect square ; If N is sum of 2 perfect squares ; If N is sum of 3 perfect squares ; Otherwise , N is the sum of 4 perfect squares ; Driver code ; Given number ; Function call
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool isPerfectSquare ( int N ) { int floorSqrt = sqrt ( N ) ; return ( N == floorSqrt * floorSqrt ) ; } bool legendreFunction ( int N ) { while ( N % 4 == 0 ) N /= 4 ; if ( N % 8 != 7 ) return true ; else return false ; } int minSquares ( int N ) { if ( isPerfectSquare ( N ) ) return 1 ; for ( int i = 1 ; i * i < N ; i ++ ) { if ( isPerfectSquare ( N - i * i ) ) return 2 ; } if ( legendreFunction ( N ) ) return 3 ; return 4 ; } int main ( ) { int N = 123 ; cout << minSquares ( N ) ; return 0 ; }
Check if N leaves only distinct remainders on division by all values up to K | C ++ Program to check if all remainders are distinct or not ; Function to check and return if all remainders are distinct ; Stores the remainder ; Calculate the remainder ; If remainder already occurred ; Insert into the set ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool is_distinct ( long long n , long long k ) { unordered_set < long long > s ; for ( int i = 1 ; i <= k ; i ++ ) { long long tmp = n % i ; if ( s . find ( tmp ) != s . end ( ) ) { return false ; } s . insert ( tmp ) ; } return true ; } int main ( ) { long long N = 5 , K = 3 ; if ( is_distinct ( N , K ) ) cout << " Yes " ; else cout << " No " ; return 0 ; }
Count of multiplicative partitions of N | C ++ implementation to find the multiplicative partitions of the given number N ; Function to return number of ways of factoring N with all factors greater than 1 ; Variable to store number of ways of factoring n with all factors greater than 1 ; Driver code ; 2 is the minimum factor of number other than 1. So calling recursive function to find number of ways of factoring N with all factors greater than 1
#include <bits/stdc++.h> NEW_LINE using namespace std ; static int getDivisors ( int min , int n ) { int total = 0 ; for ( int i = min ; i < n ; ++ i ) { if ( n % i == 0 && n / i >= i ) { ++ total ; if ( n / i > i ) total += getDivisors ( i , n / i ) ; } } return total ; } int main ( ) { int n = 30 ; cout << 1 + getDivisors ( 2 , n ) ; return 0 ; }
Find last 2 survivors in N persons standing in a circle after killing next to immediate neighbour | C ++ implementation of the approach ; Node for a Linked List ; Function to find the last 2 survivors ; Total is the count of alive people ; Initiating the list of n people ; Total != 2 is terminating condition because at last only two - person will remain alive ; Del represent next person to be deleted or killed ; Last two person to survive ( in any order ) ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; struct Node { int val ; struct Node * next ; Node ( int _val ) { val = _val ; next = NULL ; } } ; void getLastTwoPerson ( int n ) { int total = n ; struct Node * head = new Node ( 1 ) ; struct Node * temp = head ; for ( int i = 2 ; i <= n ; i ++ ) { temp -> next = new Node ( i ) ; temp = temp -> next ; } temp -> next = head ; temp = head ; struct Node * del ; while ( total != 2 ) { del = temp -> next -> next ; temp -> next -> next = temp -> next -> next -> next ; temp = temp -> next ; free ( del ) ; total -= 1 ; } cout << temp -> val << " ▁ " << temp -> next -> val ; } int main ( ) { int n = 2 ; getLastTwoPerson ( n ) ; return 0 ; }
Philaland Coin | TCS Mockvita 2020 | C ++ implementation to find the minimum number of denominations required for any number ; Function to find the minimum number of denomminations required ; Driver Code ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; int findMinDenomin ( int n ) { return log2 ( n ) + 1 ; } int main ( ) { int n = 10 ; cout << findMinDenomin ( n ) ; return 0 ; }
Content of a Polynomial | C ++ implementation to find the content of the polynomial ; Function to find the content of the polynomial ; Loop to iterate over the elements of the array ; __gcd ( a , b ) is a inbuilt function for Greatest Common Divisor ; Driver Code ; Function call
#include <bits/stdc++.h> NEW_LINE using namespace std ; #define newl " NEW_LINE " #define ll long long NEW_LINE #define pb push_back NEW_LINE int findContent ( int arr [ ] , int n ) { int content = arr [ 0 ] ; for ( int i = 1 ; i < n ; i ++ ) { content = __gcd ( content , arr [ i ] ) ; } return content ; } int main ( ) { int n = 3 ; int arr [ ] = { 9 , 6 , 12 } ; cout << findContent ( arr , n ) ; return 0 ; }
Check if the given array is same as its inverse permutation | C ++ Program to implement the above approach ; Function to check if the inverse permutation of the given array is same as the original array ; Stores the inverse permutation ; Generate the inverse permutation ; Check if the inverse permutation is same as the given array ; Driver Code
#include <iostream> NEW_LINE using namespace std ; void inverseEqual ( int arr [ ] , int n ) { int brr [ n ] ; for ( int i = 0 ; i < n ; i ++ ) { int present_index = arr [ i ] - 1 ; brr [ present_index ] = i + 1 ; } for ( int i = 0 ; i < n ; i ++ ) { if ( arr [ i ] != brr [ i ] ) { cout << " No " << endl ; return ; } } cout << " Yes " << endl ; } int main ( ) { int n = 4 ; int arr [ n ] = { 1 , 4 , 3 , 2 } ; inverseEqual ( arr , n ) ; return 0 ; }
Check if the given array is same as its inverse permutation | C ++ Program to implement the above approach ; Function to check if the inverse permutation of the given array is same as the original array ; Check the if inverse permutation is not same ; Driver Code ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool inverseEqual ( int arr [ ] , int n ) { for ( int i = 0 ; i < n ; i ++ ) if ( arr [ arr [ i ] - 1 ] != i + 1 ) return false ; return true ; } int main ( ) { int n = 4 ; int arr [ n ] = { 1 , 4 , 3 , 2 } ; cout << ( inverseEqual ( arr , n ) ? " Yes " : " No " ) ; return 0 ; }
Linear Congruence method for generating Pseudo Random Numbers | C ++ implementation of the above approach ; Function to generate random numbers ; Initialize the seed state ; Traverse to generate required numbers of random numbers ; Follow the linear congruential method ; Driver Code ; Seed value ; Modulus parameter ; Multiplier term ; Increment term ; Number of Random numbers to be generated ; To store random numbers ; Function Call ; Print the generated random numbers
#include <bits/stdc++.h> NEW_LINE using namespace std ; void linearCongruentialMethod ( int Xo , int m , int a , int c , vector < int > & randomNums , int noOfRandomNums ) { randomNums [ 0 ] = Xo ; for ( int i = 1 ; i < noOfRandomNums ; i ++ ) { randomNums [ i ] = ( ( randomNums [ i - 1 ] * a ) + c ) % m ; } } int main ( ) { int Xo = 5 ; int m = 7 ; int a = 3 ; int c = 3 ; int noOfRandomNums = 10 ; vector < int > randomNums ( noOfRandomNums ) ; linearCongruentialMethod ( Xo , m , a , c , randomNums , noOfRandomNums ) ; for ( int i = 0 ; i < noOfRandomNums ; i ++ ) { cout << randomNums [ i ] << " ▁ " ; } return 0 ; }
Multiplicative Congruence method for generating Pseudo Random Numbers | C ++ implementation of the above approach ; Function to generate random numbers ; Initialize the seed state ; Traverse to generate required numbers of random numbers ; Follow the multiplicative congruential method ; Driver Code ; seed value ; modulus parameter ; multiplier term ; Number of Random numbers to be generated ; To store random numbers ; Function Call ; Print the generated random numbers
#include <bits/stdc++.h> NEW_LINE using namespace std ; void multiplicativeCongruentialMethod ( int Xo , int m , int a , vector < int > & randomNums , int noOfRandomNums ) { randomNums [ 0 ] = Xo ; for ( int i = 1 ; i < noOfRandomNums ; i ++ ) { randomNums [ i ] = ( randomNums [ i - 1 ] * a ) % m ; } } int main ( ) { int Xo = 3 ; int m = 15 ; int a = 7 ; int noOfRandomNums = 10 ; vector < int > randomNums ( noOfRandomNums ) ; multiplicativeCongruentialMethod ( Xo , m , a , randomNums , noOfRandomNums ) ; for ( int i = 0 ; i < noOfRandomNums ; i ++ ) { cout << randomNums [ i ] << " ▁ " ; } return 0 ; }
Product of divisors of a number from a given list of its prime factors | C ++ Program to implement the above approach ; Function to calculate ( a ^ b ) % m ; Function to calculate and return the product of divisors ; Stores the frequencies of prime divisors ; Iterate over the prime divisors ; Update the product ; Update the count of divisors ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int MOD = 1000000007 ; int power ( int a , int b , int m ) { a %= m ; int res = 1 ; while ( b > 0 ) { if ( b & 1 ) res = ( ( res % m ) * ( a % m ) ) % m ; a = ( ( a % m ) * ( a % m ) ) % m ; b >>= 1 ; } return res % m ; } int productOfDivisors ( int p [ ] , int n ) { map < int , int > prime ; for ( int i = 0 ; i < n ; i ++ ) { prime [ p [ i ] ] ++ ; } int product = 1 , d = 1 ; for ( auto itr : prime ) { int val = power ( itr . first , ( itr . second ) * ( itr . second + 1 ) / 2 , MOD ) ; product = ( power ( product , itr . second + 1 , MOD ) * power ( val , d , MOD ) ) % MOD ; d = ( d * ( itr . second + 1 ) ) % ( MOD - 1 ) ; } return product ; } int main ( ) { int arr [ ] = { 11 , 11 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << productOfDivisors ( arr , n ) ; }
Print all proper fractions with denominators less than equal to N | C ++ program to implement the above approach ; Function to print all proper fractions ; If the numerator and the denominator are coprime ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void printFractions ( int n ) { for ( int i = 1 ; i < n ; i ++ ) { for ( int j = i + 1 ; j <= n ; j ++ ) { if ( __gcd ( i , j ) == 1 ) { string a = to_string ( i ) ; string b = to_string ( j ) ; cout << a + " / " + b << " , ▁ " ; } } } } int main ( ) { int n = 3 ; printFractions ( n ) ; return 0 ; }
Maximum number of objects that can be created as per given conditions | C ++ program for the above problem ; Function for finding the maximum number of objects from N type - 1 and M type - 2 items ; storing minimum of N and M ; storing maximum number of objects from given items ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int numberOfObjects ( int N , int M ) { int initial = min ( N , M ) ; int final = ( N + M ) / 3 ; return min ( initial , final ) ; } int main ( ) { int N = 8 ; int M = 7 ; cout << numberOfObjects ( N , M ) << endl ; return 0 ; }
Square root of a number by Repeated Subtraction method | C ++ implementation of the above approach ; Function to return the square root of the given number ; Subtract n - th odd number ; Return the result ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int SquareRoot ( int num ) { int count = 0 ; for ( int n = 1 ; n <= num ; n += 2 ) { num = num - n ; count += 1 ; if ( num == 0 ) break ; } return count ; } int main ( ) { int N = 81 ; cout << SquareRoot ( N ) ; }
Maximize count of distinct elements possible in an Array from the given operation | C ++ program to find the maximum possible distinct elements that can be obtained from the array by performing the given operations ; Function to find the gcd of two numbers ; Function to calculate and return the count of maximum possible distinct elements in the array ; Find the maximum element ; Base Case ; Finding the gcd of first two element ; Calculate Gcd of the array ; Return the total count of distinct elements ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int gcd ( int x , int y ) { if ( x == 0 ) return y ; return gcd ( y % x , x ) ; } int findDistinct ( int arr [ ] , int n ) { int maximum = * max_element ( arr , arr + n ) ; if ( n == 1 ) return 1 ; if ( n == 2 ) { return ( maximum / gcd ( arr [ 0 ] , arr [ 1 ] ) ) ; } int k = gcd ( arr [ 0 ] , arr [ 1 ] ) ; for ( int i = 2 ; i < n ; i ++ ) { k = gcd ( k , arr [ i ] ) ; } return ( maximum / k ) ; } int main ( ) { int arr [ ] = { 1 , 2 , 3 , 5 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << findDistinct ( arr , n ) ; return 0 ; }
Find indices of all local maxima and local minima in an Array | C ++ program for the above approach ; Function to find all the local maxima and minima in the given array arr [ ] ; Empty vector to store points of local maxima and minima ; Checking whether the first point is local maxima or minima or none ; Iterating over all points to check local maxima and local minima ; Condition for local minima ; Condition for local maxima ; Checking whether the last point is local maxima or minima or none ; Print all the local maxima and local minima indexes stored ; Driver Code ; Given array arr [ ] ; Function call
#include <bits/stdc++.h> NEW_LINE using namespace std ; void findLocalMaximaMinima ( int n , int arr [ ] ) { vector < int > mx , mn ; if ( arr [ 0 ] > arr [ 1 ] ) mx . push_back ( 0 ) ; else if ( arr [ 0 ] < arr [ 1 ] ) mn . push_back ( 0 ) ; for ( int i = 1 ; i < n - 1 ; i ++ ) { if ( ( arr [ i - 1 ] > arr [ i ] ) and ( arr [ i ] < arr [ i + 1 ] ) ) mn . push_back ( i ) ; else if ( ( arr [ i - 1 ] < arr [ i ] ) and ( arr [ i ] > arr [ i + 1 ] ) ) mx . push_back ( i ) ; } if ( arr [ n - 1 ] > arr [ n - 2 ] ) mx . push_back ( n - 1 ) ; else if ( arr [ n - 1 ] < arr [ n - 2 ] ) mn . push_back ( n - 1 ) ; if ( mx . size ( ) > 0 ) { cout << " Points ▁ of ▁ Local ▁ maxima ▁ are ▁ : ▁ " ; for ( int a : mx ) cout << a << " ▁ " ; cout << endl ; } else cout << " There ▁ are ▁ no ▁ points ▁ of ▁ " << " Local ▁ Maxima ▁ STRNEWLINE " ; if ( mn . size ( ) > 0 ) { cout << " Points ▁ of ▁ Local ▁ minima ▁ are ▁ : ▁ " ; for ( int a : mn ) cout << a << " ▁ " ; cout << endl ; } else cout << " There ▁ are ▁ no ▁ points ▁ of ▁ " << " Local ▁ Minima ▁ STRNEWLINE " ; } int main ( ) { int N = 9 ; int arr [ ] = { 10 , 20 , 15 , 14 , 13 , 25 , 5 , 4 , 3 } ; findLocalMaximaMinima ( N , arr ) ; return 0 ; }
Smallest N digit number with none of its digits as its divisor | C ++ Program for the given problem ; Function to calculate power ; Function to check if the N - digit number satisfies the given condition or not ; Getting the last digit ; Every number is divisible by 1 and dividing a number by 0 isn 't possible. Thus numbers with 0 as a digit must be discarded. ; If any digit divides the number , return false ; If no digit divides the number , return true ; ; Function to find the smallest number not divisible by any of its digits . ; Get the lower range of n digit number ; Get the high range of n digit number ; check all the N - digit numbers ; If the first number to satify the constraints is found print it , set the flag value and break out of the loop . ; If no such digit found , return - 1 as per problem statement ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int power ( int a , int b ) { if ( b == 0 ) return 1 ; if ( b == 1 ) return a ; int tmp = power ( a , b / 2 ) ; int result = tmp * tmp ; if ( b % 2 == 1 ) result *= a ; return result ; } bool check ( int n ) { int temp = n ; while ( temp > 0 ) { int last_digit = temp % 10 ; if ( last_digit == 0 last_digit == 1 ) return false ; if ( n % last_digit == 0 ) return false ; temp = temp / 10 ; } return true ; } void solve ( int n ) { int L = power ( 10 , n - 1 ) ; int R = power ( 10 , n ) - 1 ; int flag = 0 ; for ( int i = L ; i <= R ; i ++ ) { bool answer = check ( i ) ; if ( answer == true ) { cout << i << endl ; flag ++ ; break ; } } if ( flag == 0 ) cout << -1 << endl ; } int main ( ) { int N = 4 ; solve ( N ) ; }
C / C ++ program for Armstrong Numbers | C ++ program to find Armstrong number ; Function to calculate N raised to the power D ; Function to calculate the order of the number ; For each digit ; Function to check whether the given number is Armstrong number or not ; To find order of N ; Traverse each digit ; If satisfies Armstrong condition ; Driver Code ; Given Number N ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; int power ( int N , unsigned int D ) { if ( D == 0 ) return 1 ; if ( D % 2 == 0 ) return power ( N , D / 2 ) * power ( N , D / 2 ) ; return N * power ( N , D / 2 ) * power ( N , D / 2 ) ; } int order ( int N ) { int r = 0 ; while ( N ) { r ++ ; N = N / 10 ; } return r ; } int isArmstrong ( int N ) { int D = order ( N ) ; int temp = N , sum = 0 ; while ( temp ) { int Ni = temp % 10 ; sum += power ( Ni , D ) ; temp = temp / 10 ; } if ( sum == N ) return 1 ; else return 0 ; } int main ( ) { int N = 153 ; if ( isArmstrong ( N ) == 1 ) cout << " True " ; else cout << " False " ; return 0 ; }
Cost of creating smallest subsequence with sum of difference between adjacent elements maximum | ; initializing cost = 0 ; to store the removed element ; this will store the sum of the subsequence ; checking all the element of the vector ; storing the value of arr [ i ] in temp variable ; if the situation like arr [ i - 1 ] < arr [ i ] < arr [ i + 1 ] or arr [ i - 1 ] > arr [ i ] > arr [ i + 1 ] occur remove arr [ i ] i . e , temp from sequence ; insert the element in the set removedElements ; storing the value of arr [ i ] in temp ; taking the element not in removedElements ; adding the value of elements of subsequence ; if we have to remove the element then we need to add the cost associated with the element ; printing the sum of the subsequence with minimum length possible ; printing the cost incurred in creating subsequence ; Driver code ; calling the function
#include <bits/stdc++.h> NEW_LINE using namespace std ; void costOfSubsequence ( int N , int arr [ ] , int costArray [ ] ) { int i , temp ; int cost = 0 ; set < int > removedElements ; int ans = 0 ; for ( i = 1 ; i < ( N - 1 ) ; i ++ ) { temp = arr [ i ] ; if ( ( ( arr [ i - 1 ] < temp ) && ( temp < arr [ i + 1 ] ) ) || ( ( arr [ i - 1 ] > temp ) && ( temp > arr [ i + 1 ] ) ) ) { removedElements . insert ( temp ) ; } } for ( i = 0 ; i < ( N ) ; i ++ ) { temp = arr [ i ] ; if ( ! ( removedElements . count ( temp ) > 0 ) ) { ans += arr [ i ] ; } else { cost += costArray [ i ] ; } } cout << ans << " , ▁ " ; cout << cost << endl ; } int main ( ) { int N ; N = 4 ; int arr [ N ] = { 1 , 3 , 4 , 2 } ; int costArray [ N ] = { 0 , 1 , 0 , 0 } ; costOfSubsequence ( N , arr , costArray ) ; return 0 ; }
Count of natural numbers in range [ L , R ] which are relatively prime with N | C ++ code to count of natural numbers in range [ L , R ] which are relatively prime with N ; container of all the primes up to sqrt ( n ) ; Function to calculate prime factors of n ; run the sieve of Eratosthenes ; 0 ( false ) means prime , 1 ( true ) means not prime ; no even number is prime except for 2 ; all the multiples of each each prime numbers are non - prime ; get all the primes in prime vector ; Count the number of numbers up to m which are divisible by given prime numbers ; Run from i = 000. . 0 to i = 111. . 1 or check all possible subsets of the array ; if the number of set bits is odd , then add to the number of multiples ; Function calculates all number not greater than ' m ' which are relatively prime with n . ; if square of the prime number is greater than ' n ' , it can ' t ▁ ▁ be ▁ a ▁ factor ▁ of ▁ ' n ' ; if prime is a factor of n then increment count ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; #define maxN (long long)1000000000000 NEW_LINE vector < int > prime ; void sieve ( long long n ) { bool check [ 1000007 ] = { 0 } ; long long i , j ; check [ 0 ] = 1 , check [ 1 ] = 1 , check [ 2 ] = 0 ; for ( i = 4 ; i <= n ; i += 2 ) check [ i ] = true ; for ( i = 3 ; i * i <= n ; i += 2 ) if ( ! check [ i ] ) { for ( j = i * i ; j <= n ; j += 2 * i ) check [ j ] = true ; } prime . push_back ( 2 ) ; for ( int i = 3 ; i <= n ; i += 2 ) if ( ! check [ i ] ) prime . push_back ( i ) ; return ; } long long count ( long long a [ ] , int n , long long m ) { long long parity [ 3 ] = { 0 } ; for ( int i = 1 ; i < ( 1 << n ) ; i ++ ) { long long mult = 1 ; for ( int j = 0 ; j < n ; j ++ ) if ( i & ( 1 << j ) ) mult *= a [ j ] ; parity [ __builtin_popcount ( i ) & 1 ] += ( m / mult ) ; } return parity [ 1 ] - parity [ 0 ] ; } long long countRelPrime ( long long n , long long m ) { long long a [ 20 ] ; int i = 0 , j = 0 ; long long pz = prime . size ( ) ; while ( n != 1 && i < pz ) { if ( ( long long ) prime [ i ] * ( long long ) prime [ i ] > n ) break ; if ( n % prime [ i ] == 0 ) a [ j ] = ( long long ) prime [ i ] , j ++ ; while ( n % prime [ i ] == 0 ) n /= prime [ i ] ; i ++ ; } if ( n != 1 ) a [ j ] = n , j ++ ; return m - count ( a , j , m ) ; } void countRelPrimeInRange ( long long n , long long l , long long r ) { sieve ( sqrt ( maxN ) ) ; long long result = countRelPrime ( n , r ) - countRelPrime ( n , l - 1 ) ; cout << result << " STRNEWLINE " ; } int main ( ) { long long N = 7 , L = 3 , R = 9 ; countRelPrimeInRange ( N , L , R ) ; return 0 ; }
C / C ++ Program to find Prime Numbers between given range | C ++ program to find the prime numbers between a given interval ; Function for print prime number in given range ; Traverse each number in the interval with the help of for loop ; Skip 0 and 1 as they are neither prime nor composite ; flag variable to tell if i is prime or not ; Iterate to check if i is prime or not ; flag = 1 means i is prime and flag = 0 means i is not prime ; Driver Code ; Given Range ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; void primeInRange ( int L , int R ) { int flag ; for ( int i = L ; i <= R ; i ++ ) { if ( i == 1 i == 0 ) continue ; flag = 1 ; for ( int j = 2 ; j <= i / 2 ; ++ j ) { if ( i % j == 0 ) { flag = 0 ; break ; } } if ( flag == 1 ) cout << i << " ▁ " ; } } int main ( ) { int L = 1 ; int R = 10 ; primeInRange ( L , R ) ; return 0 ; }
XOR of a subarray ( range of elements ) | Set 2 | C ++ program to find XOR in a range from L to R ; Function to find XOR in a range from L to R ; Compute xor from arr [ 0 ] to arr [ i ] ; process every query in constant time ; if L == 0 ; Driver Code ; query [ ]
#include <bits/stdc++.h> NEW_LINE using namespace std ; void find_Xor ( int arr [ ] , pair < int , int > query [ ] , int N , int Q ) { for ( int i = 1 ; i < N ; i ++ ) { arr [ i ] = arr [ i ] ^ arr [ i - 1 ] ; } int ans = 0 ; for ( int i = 0 ; i < Q ; i ++ ) { if ( query [ i ] . first == 0 ) ans = arr [ query [ i ] . second ] ; else ans = arr [ query [ i ] . first - 1 ] ^ arr [ query [ i ] . second ] ; cout << ans << endl ; } } int main ( ) { int arr [ ] = { 3 , 2 , 4 , 5 , 1 , 1 , 5 , 3 } ; int N = 8 ; int Q = 2 ; pair < int , int > query [ Q ] = { { 1 , 4 } , { 3 , 7 } } ; find_Xor ( arr , query , N , Q ) ; return 0 ; }
Generate an alternate increasing and decreasing Array | C ++ program to Generate an increasing and decreasing array ; Function that returns generated array ; Dynamically allocate array ; START = 0 , END = N ; iterate over array ; if Str [ i ] == ' I ' assign arr [ i ] as START and increment START ; if str [ i ] == ' D ' assign arr [ i ] as END and decrement END ; assign A [ N ] as START ; return starting address of array A ; Driver Program
#include <iostream> NEW_LINE using namespace std ; int * DiStirngMatch ( string Str ) { int N = Str . length ( ) ; int * arr = new int [ N ] ; int START = 0 , END = N ; for ( int i = 0 ; i < N ; i ++ ) { if ( Str [ i ] == ' I ' ) arr [ i ] = START ++ ; if ( Str [ i ] == ' D ' ) arr [ i ] = END -- ; } arr [ N ] = START ; return arr ; } int main ( ) { string Str = " IDID " ; int N = Str . length ( ) ; int * ptr = DiStirngMatch ( Str ) ; for ( int i = 0 ; i <= N ; i ++ ) cout << ptr [ i ] << " ▁ " ; return 0 ; }
Count of square free divisors of a given number | C ++ Program to find the square free divisors of a given number ; The function to check if a number is prime or not ; If the number is even then its not prime ; Driver Code ; Stores the count of distinct prime factors ; Print the number of square - free divisors
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool IsPrime ( int i ) { if ( i % 2 == 0 && i != 2 ) return false ; else { for ( int j = 3 ; j <= sqrt ( i ) ; j += 2 ) { if ( i % j == 0 ) return false ; } return true ; } } int main ( ) { int c = 0 ; int N = 72 ; for ( int i = 2 ; i <= sqrt ( N ) ; i ++ ) { if ( IsPrime ( i ) ) { if ( N % i == 0 ) { c ++ ; if ( IsPrime ( N / i ) && i != ( N / i ) ) { c ++ ; } } } } cout << pow ( 2 , c ) - 1 << endl ; return 0 ; }
Generate Array whose difference of each element with its left yields the given Array | C ++ program for the above approach ; Function to find the sequence ; initializing 1 st element ; Creating sequence in terms of x ; Finding min element ; Finding value of x ; Creating original sequence ; Output original sequence ; Driver function
#include <bits/stdc++.h> NEW_LINE using namespace std ; void find_seq ( int arr [ ] , int m , int n ) { int b [ n ] ; int x = 0 ; b [ 0 ] = x ; for ( int i = 0 ; i < n - 1 ; i ++ ) { b [ i + 1 ] = x + arr [ i ] + b [ i ] ; } int mn = n ; for ( int i = 0 ; i < n ; i ++ ) { mn = min ( mn , b [ i ] ) ; } x = 1 - mn ; for ( int i = 0 ; i < n ; i ++ ) { b [ i ] += x ; } for ( int i = 0 ; i < n ; i ++ ) { cout << b [ i ] << " ▁ " ; } cout << endl ; } int main ( ) { int N = 3 ; int arr [ ] = { -2 , 1 } ; int M = sizeof ( arr ) / sizeof ( int ) ; find_seq ( arr , M , N ) ; return 0 ; }
Check whether count of odd and even factors of a number are equal | C ++ solution for the above approach ; Function to check condition ; Initialize even_count and od_count ; loop runs till square root ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; #define lli long long int NEW_LINE void isEqualFactors ( lli N ) { lli ev_count = 0 , od_count = 0 ; for ( lli i = 1 ; i <= sqrt ( N ) + 1 ; i ++ ) { if ( N % i == 0 ) { if ( i == N / i ) { if ( i % 2 == 0 ) ev_count += 1 ; else od_count += 1 ; } else { if ( i % 2 == 0 ) ev_count += 1 ; else od_count += 1 ; if ( ( N / i ) % 2 == 0 ) ev_count += 1 ; else od_count += 1 ; } } } if ( ev_count == od_count ) cout << " YES " << endl ; else cout << " NO " << endl ; } int main ( ) { lli N = 10 ; isEqualFactors ( N ) ; return 0 ; }
Check whether count of odd and even factors of a number are equal | C ++ code for the above approach ; Function to check condition ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; #define lli long long int NEW_LINE void isEqualFactors ( lli N ) { if ( ( N % 2 == 0 ) and ( N % 4 != 0 ) ) cout << " YES " << endl ; else cout << " NO " << endl ; } int main ( ) { lli N = 10 ; isEqualFactors ( N ) ; N = 125 ; isEqualFactors ( N ) ; return 0 ; }
Count of all values of N in [ L , R ] such that count of primes upto N is also prime | C ++ program for the above approach ; Function to count the number of crazy primes in the given range [ L , R ] ; Stores all primes ; Stores count of primes ; Stores if frequency of primes is a prime or not upto each index ; Sieve of Eratosthenes ; Count primes ; If i is a prime ; Stores frequency of primes ; If the frequency of primes is a prime ; Increase count of required numbers ; Return the required count ; Driver Code ; Given Range ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; int count_crazy_primes ( int L , int R ) { int prime [ R + 1 ] = { 0 } ; int countPrime [ R + 1 ] = { 0 } ; int freqPrime [ R + 1 ] = { 0 } ; prime [ 0 ] = prime [ 1 ] = 1 ; for ( int p = 2 ; p * p <= R ; p ++ ) { if ( prime [ p ] == 0 ) { for ( int i = p * p ; i <= R ; i += p ) prime [ i ] = 1 ; } } for ( int i = 1 ; i <= R ; i ++ ) { countPrime [ i ] = countPrime [ i - 1 ] ; if ( ! prime [ i ] ) { countPrime [ i ] ++ ; } } for ( int i = 1 ; i <= R ; i ++ ) { freqPrime [ i ] = freqPrime [ i - 1 ] ; if ( ! prime [ countPrime [ i ] ] ) { freqPrime [ i ] ++ ; } } return ( freqPrime [ R ] - freqPrime [ L - 1 ] ) ; } int main ( ) { int L = 4 , R = 12 ; cout << count_crazy_primes ( L , R ) ; return 0 ; }
Largest N digit number in Base B | C ++ program for the approach ; Function to print the largest N - digit numbers of base b ; Find the largest N digit number in base b using the formula B ^ N - 1 ; Print the largest number ; Driver Code ; Given Number and Base ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; void findNumbers ( int n , int b ) { int largest = pow ( b , n ) - 1 ; cout << largest << endl ; } int main ( ) { int N = 2 , B = 5 ; findNumbers ( N , B ) ; return 0 ; }
Generate an Array such with elements maximized through swapping bits | C ++ implementation to find maximum sequence by swapping bits ; Function to generate the maximized array elements ; Traverse the array ; Iterate to count set and unset bits ; Count of unset bits ; Count of set bits ; Bitwise right shift ; Shifting all 1 ' s ▁ to ▁ MSB ▁ ▁ and ▁ 0' s to LSB ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void maximizedArray ( int arr [ ] , int N ) { int num , i = 0 ; while ( N -- ) { num = arr [ i ] ; int one = 0 ; int zero = 0 ; while ( num ) { if ( num % 2 == 0 ) { zero ++ ; } else { one ++ ; } num = num >> 1 ; } for ( int j = zero ; j < ( one + zero ) ; j ++ ) { num += ( 1 << j ) ; } cout << num ; i ++ ; if ( N > 0 ) cout << " , ▁ " ; } } int main ( ) { int arr [ ] = { 8 , 15 , 9 , 10 , 14 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; maximizedArray ( arr , N ) ; return 0 ; }
Find the ratio of LCM to GCD of a given Array | C ++ Program to implement above approach ; Function to calculate and return GCD of the given array ; Initialise GCD ; Once GCD is 1 , it will always be 1 with all other elements ; Return GCD ; Function to calculate and return LCM of the given array ; Initialise LCM ; LCM of two numbers is evaluated as [ ( a * b ) / gcd ( a , b ) ] ; Return LCM ; Function to print the ratio of LCM to GCD of the given array ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int findGCD ( int arr [ ] , int n ) { int gcd = arr [ 0 ] ; for ( int i = 1 ; i < n ; i ++ ) { gcd = __gcd ( arr [ i ] , gcd ) ; if ( gcd == 1 ) { return 1 ; } } return gcd ; } int findLCM ( int arr [ ] , int n ) { int lcm = arr [ 0 ] ; for ( int i = 1 ; i < n ; i ++ ) { lcm = ( ( ( arr [ i ] * lcm ) ) / ( __gcd ( arr [ i ] , lcm ) ) ) ; } return lcm ; } void findRatio ( int arr [ ] , int n ) { int gcd = findGCD ( arr , n ) ; int lcm = findLCM ( arr , n ) ; cout << lcm / gcd << " : " << 1 << endl ; } int main ( ) { int arr [ ] = { 6 , 12 , 36 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; findRatio ( arr , N ) ; return 0 ; }
Minimum operations required to make all Array elements divisible by K | C ++ implementation to find the Minimum number of moves required to update the array such that each of its element is divisible by K ; Function to find the Minimum number of moves required to update the array such that each of its element is divisible by K ; Initialize Map data structure ; Iterate for all the elements of the array ; Calculate the value to be added ; Check if the value equals to 0 then simply continue ; Check if the value to be added is present in the map ; Update the answer ; Print the required result We need to add 1 to maxX because we cant ignore the first move where initially X = 0 and we need to increase it by 1 to make some changes in array ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void compute ( int a [ ] , int N , int K ) { map < long , long > eqVal ; long maxX = 0 ; for ( int i = 0 ; i < N ; i ++ ) { long val = a [ i ] % K ; val = ( val == 0 ? 0 : K - val ) ; if ( val == 0 ) continue ; if ( eqVal . find ( val ) != eqVal . end ( ) ) { long numVal = eqVal [ val ] ; maxX = max ( maxX , val + ( K * numVal ) ) ; eqVal [ val ] ++ ; } else { eqVal [ val ] ++ ; maxX = max ( maxX , val ) ; } } cout << ( maxX == 0 ? 0 : maxX + 1 ) << endl ; } int main ( ) { int K = 3 ; int a [ ] = { 1 , 2 , 2 , 18 } ; int N = sizeof ( a ) / sizeof ( a [ 0 ] ) ; compute ( a , N , K ) ; return 0 ; }
Array sum after replacing all occurrences of X by Y for Q queries | C ++ implementation to find the sum of the array for the given Q queries ; Function that print the sum of the array for Q queries ; Stores the frequencies of array elements ; Calculate the sum of the initial array and store the frequency of each element in map ; Iterate for all the queries ; Store query values ; Decrement the sum accordingly ; Increment the sum accordingly ; Set count of Y [ i ] ; Reset count of X [ i ] ; Print the sum ; Driver Code ; Function call
#include <bits/stdc++.h> NEW_LINE using namespace std ; void sumOfTheArrayForQuery ( int * A , int N , int * X , int * Y , int Q ) { int sum = 0 ; unordered_map < int , int > count ; for ( int i = 0 ; i < N ; i ++ ) { sum += A [ i ] ; count [ A [ i ] ] ++ ; } for ( int i = 0 ; i < Q ; i ++ ) { int x = X [ i ] , y = Y [ i ] ; sum -= count [ X [ i ] ] * X [ i ] ; sum += count [ X [ i ] ] * Y [ i ] ; count [ Y [ i ] ] += count [ X [ i ] ] ; count [ X [ i ] ] = 0 ; cout << sum << " ▁ " ; } } int main ( ) { int arr [ ] = { 1 , 2 , 1 , 3 , 2 } ; int X [ ] = { 2 , 3 , 5 } ; int Y [ ] = { 3 , 1 , 2 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; int Q = sizeof ( X ) / sizeof ( X [ 0 ] ) ; sumOfTheArrayForQuery ( arr , N , X , Y , Q ) ; return 0 ; }
Maximum OR value of a pair in an Array | Set 2 | C ++ implementation of the approach above ; Function to return the maximum bitwise OR for any pair of the given array in O ( n ) time complexity . ; Find the maximum element in the array ; Stores the maximum OR value ; Traverse the array and perform Bitwise OR between every array element with the maximum element ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int maxOR ( int arr [ ] , int n ) { int max_value = * max_element ( arr , arr + n ) ; int ans = 0 ; for ( int i = 0 ; i < n ; i ++ ) { ans = max ( ans , ( max_value arr [ i ] ) ) ; } return ans ; } int main ( ) { int arr [ ] = { 3 , 6 , 8 , 16 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << maxOR ( arr , n ) ; return 0 ; }
Count of elements on the left which are divisible by current element | Set 2 | C ++ implementation of the approach ; Utility function to print the elements of the array ; Function to increment the count for each factor of given val ; Function to generate and print the required array ; Find max element of array ; Create count array of maxi size ; For every element of the array ; Count [ A [ i ] ] denotes how many previous elements are there whose factor is the current element . ; Increment in count array for factors of A [ i ] ; Print the generated array ; 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 IncrementFactors ( int count [ ] , int val ) { for ( int i = 1 ; i * i <= val ; i ++ ) { if ( val % i == 0 ) { if ( i == val / i ) { count [ i ] ++ ; } else { count [ i ] ++ ; count [ val / i ] ++ ; } } } } void generateArr ( int A [ ] , int n ) { int B [ n ] ; int maxi = * max_element ( A , A + n ) ; int count [ maxi + 1 ] = { 0 } ; for ( int i = 0 ; i < n ; i ++ ) { B [ i ] = count [ A [ i ] ] ; IncrementFactors ( count , A [ i ] ) ; } printArr ( B , n ) ; } int main ( ) { int arr [ ] = { 8 , 1 , 28 , 4 , 2 , 6 , 7 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; generateArr ( arr , n ) ; return 0 ; }
Minimum changes required to make all Array elements Prime | C ++ Program to implement the above approach ; Function to generate all primes ; If p is a prime ; Mark all its multiples as non - prime ; Store all prime numbers ; Return the list of primes ; Function to calculate the minimum increments to convert every array elements to a prime ; Extract maximum element of the given array ; Extract the index which has the next greater prime ; Store the difference between the prime and the array element ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; vector < int > SieveOfEratosthenes ( int n ) { bool prime [ 2 * n + 1 ] ; memset ( prime , true , sizeof ( prime ) ) ; for ( int p = 2 ; p * p <= 2 * n ; p ++ ) { if ( prime [ p ] == true ) { for ( int i = p * p ; i <= 2 * n ; i += p ) prime [ i ] = false ; } } vector < int > primes ; for ( int p = 2 ; p <= 2 * n ; p ++ ) if ( prime [ p ] ) primes . push_back ( p ) ; return primes ; } int minChanges ( vector < int > arr ) { int n = arr . size ( ) ; int ans = 0 ; int maxi = * max_element ( arr . begin ( ) , arr . end ( ) ) ; vector < int > primes = SieveOfEratosthenes ( maxi ) ; for ( int i = 0 ; i < n ; i ++ ) { int x = lower_bound ( primes . begin ( ) , primes . end ( ) , arr [ i ] ) - primes . begin ( ) ; int minm = abs ( primes [ x ] - arr [ i ] ) ; if ( x > 1 ) { minm = min ( minm , abs ( primes [ x - 1 ] - arr [ i ] ) ) ; } ans += minm ; } return ans ; } int main ( ) { vector < int > arr = { 4 , 25 , 13 , 6 , 20 } ; cout << minChanges ( arr ) ; return 0 ; }
Sum of multiples of Array elements within a given range [ L , R ] | C ++ program for the above approach ; Function to find the sum of all multiples of N up to K ; Calculate the sum ; Return the sum ; Function to find the total sum ; If L is divisible by a [ i ] ; Otherwise ; Return the final sum ; Driver Code ; Given array arr [ ] ; Given range ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; int calcSum ( int k , int n ) { int value = ( k * n * ( n + 1 ) ) / 2 ; return value ; } int findSum ( int * a , int n , int L , int R ) { int sum = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( L % a [ i ] == 0 && L != 0 ) { sum += calcSum ( a [ i ] , R / a [ i ] ) - calcSum ( a [ i ] , ( L - 1 ) / a [ i ] ) ; } else { sum += calcSum ( a [ i ] , R / a [ i ] ) - calcSum ( a [ i ] , L / a [ i ] ) ; } } return sum ; } int main ( ) { int arr [ ] = { 2 , 7 , 3 , 8 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; int L = 7 ; int R = 20 ; cout << findSum ( arr , N , L , R ) ; return 0 ; }
Count all prime numbers in a given range whose sum of digits is also prime | C ++ program for the above approach ; Create an array for storing primes ; Create a prefix array that will contain whether sum is prime or not ; Function to find primes in the range and check whether the sum of digits of a prime number is prime or not ; Initialise Prime array arr [ ] ; Since 0 and 1 are not prime numbers we mark them as '0' ; Using Sieve Of Eratosthenes ; if the number is prime ; Mark all the multiples of i starting from square of i with '0' ie . composite ; '0' represents not prime ; Initialise a sum variable as 0 ; Check if the number is prime ; A temporary variable to store the number ; Loop to calculate the sum of digits ; Check if the sum of prime number is prime ; if prime mark 1 ; If not prime mark 0 ; computing prefix array ; Function to count the prime numbers in the range [ L , R ] ; Function Call to find primes ; Print the result ; Driver Code ; Input range ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; int maxN = 1000000 ; int arr [ 1000001 ] ; int prefix [ 1000001 ] ; void findPrimes ( ) { for ( int i = 1 ; i <= maxN ; i ++ ) arr [ i ] = 1 ; arr [ 0 ] = 0 , arr [ 1 ] = 0 ; for ( int i = 2 ; i * i <= maxN ; i ++ ) { if ( arr [ i ] == 1 ) { for ( int j = i * i ; j <= maxN ; j += i ) { arr [ j ] = 0 ; } } } int sum = 0 ; prefix [ 0 ] = 0 ; for ( int i = 1 ; i <= maxN ; i ++ ) { if ( arr [ i ] == 1 ) { int temp = i ; sum = 0 ; while ( temp > 0 ) { int x = temp % 10 ; sum += x ; temp = temp / 10 ; if ( arr [ sum ] == 1 ) { prefix [ i ] = 1 ; } else { prefix [ i ] = 0 ; } } } } for ( int i = 1 ; i <= maxN ; i ++ ) { prefix [ i ] += prefix [ i - 1 ] ; } } void countNumbersInRange ( int l , int r ) { findPrimes ( ) ; int result = prefix [ r ] - prefix [ l - 1 ] ; cout << result << endl ; } int main ( ) { int l , r ; l = 5 , r = 20 ; countNumbersInRange ( l , r ) ; return 0 ; }
Find the concentration of a solution using given Mass and Volume | C ++ program to find concentration of a solution using given Mass and Volume ; Function to calculate concentration from the given mass of solute and volume of a solution ; Driver Program
#include <bits/stdc++.h> NEW_LINE using namespace std ; double get_concentration ( double mass , double volume ) { if ( volume == 0 ) return -1 ; else return ( mass / volume ) * 1000 ; } int main ( ) { double mass , volume ; mass = 100.00 ; volume = 500.00 ; cout << get_concentration ( mass , volume ) ; return 0 ; }
Practical Numbers | C ++ program to check if a number is Practical or not . ; Returns true if there is a subset of set [ ] with sun equal to given sum ; The value of subset [ i ] [ j ] will be true if there is a subset of set [ 0. . j - 1 ] with sum equal to i ; If sum is 0 , then answer is true ; If sum is not 0 and set is empty , then answer is false ; Fill the subset table in bottom up manner ; Function to store divisors of N in a vector ; Find all divisors which divides ' num ' ; if ' i ' is divisor of ' n ' ; if both divisors are same then store it once else store both divisors ; Returns true if num is Practical ; vector to store all divisors of N ; to check all numbers from 1 to < N ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool isSubsetSum ( vector < int > & set , int n , int sum ) { bool subset [ n + 1 ] [ sum + 1 ] ; for ( int i = 0 ; i <= n ; i ++ ) subset [ i ] [ 0 ] = true ; for ( int i = 1 ; i <= sum ; i ++ ) subset [ 0 ] [ i ] = false ; for ( int i = 1 ; i <= n ; i ++ ) { for ( int j = 1 ; j <= sum ; j ++ ) { if ( j < set [ i - 1 ] ) subset [ i ] [ j ] = subset [ i - 1 ] [ j ] ; if ( j >= set [ i - 1 ] ) subset [ i ] [ j ] = subset [ i - 1 ] [ j ] || subset [ i - 1 ] [ j - set [ i - 1 ] ] ; } } return subset [ n ] [ sum ] ; } void storeDivisors ( int n , vector < int > & div ) { for ( int i = 1 ; i <= sqrt ( n ) ; i ++ ) { if ( n % i == 0 ) { if ( i == ( n / i ) ) div . push_back ( i ) ; else { div . push_back ( i ) ; div . push_back ( n / i ) ; } } } } bool isPractical ( int N ) { vector < int > div ; storeDivisors ( N , div ) ; for ( int i = 1 ; i < N ; i ++ ) { if ( ! isSubsetSum ( div , div . size ( ) , i ) ) return false ; } return true ; } int main ( ) { int N = 18 ; isPractical ( N ) ? cout << " Yes " : cout << " No " ; return 0 ; }
Super Niven Numbers | C ++ implementation to check if a number is Super Niven Number or not . ; Checks if sums of all subsets of digits array divides the number N ; to calculate length of array arr ; There are totoal 2 ^ n subsets ; Consider all numbers from 0 to 2 ^ n - 1 ; Consider binary representation of current i to decide which elements to pick . ; check sum of picked elements . ; Function to check if a number is a super - niven number ; to stor digits of N ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool isDivBySubsetSums ( vector < int > arr , int num ) { int n = arr . size ( ) ; long long total = 1 << n ; for ( long long i = 0 ; i < total ; i ++ ) { long long sum = 0 ; for ( int j = 0 ; j < n ; j ++ ) if ( i & ( 1 << j ) ) sum += arr [ j ] ; if ( sum != 0 && num % sum != 0 ) return false ; } return true ; } bool isSuperNivenNum ( int n ) { int temp = n ; vector < int > digits ; while ( n != 0 ) { int digit = n % 10 ; digits . push_back ( digit ) ; n = n / 10 ; } return isDivBySubsetSums ( digits , temp ) ; } int main ( ) { int n = 500 ; if ( isSuperNivenNum ( n ) ) cout << " yes " ; else cout << " No " ; return 0 ; }
Highly Composite Numbers | C ++ implementation for checking Highly Composite Number ; Function to count the number of divisors of the N ; sieve method for prime calculation ; Traversing through all prime numbers ; calculate number of divisor with formula total div = ( p1 + 1 ) * ( p2 + 1 ) * ... . . * ( pn + 1 ) where n = ( a1 ^ p1 ) * ( a2 ^ p2 ) . ... * ( an ^ pn ) ai being prime divisor for n and pi are their respective power in factorization ; Function to check if a number is a highly composite number ; count number of factors of N ; loop to count number of factors of every number less than N ; If any number less than N has more factors than N , then return false ; Driver code ; Given Number N ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; int divCount ( int n ) { bool hash [ n + 1 ] ; memset ( hash , true , sizeof ( hash ) ) ; for ( int p = 2 ; p * p < n ; p ++ ) if ( hash [ p ] == true ) for ( int i = p * 2 ; i < n ; i += p ) hash [ i ] = false ; int total = 1 ; for ( int p = 2 ; p <= n ; p ++ ) { if ( hash [ p ] ) { int count = 0 ; if ( n % p == 0 ) { while ( n % p == 0 ) { n = n / p ; count ++ ; } total = total * ( count + 1 ) ; } } } return total ; } bool isHighlyCompositeNumber ( int N ) { int NdivCount = divCount ( N ) ; for ( int i = 1 ; i < N ; i ++ ) { int idivCount = divCount ( i ) ; if ( idivCount >= NdivCount ) return false ; } return true ; } int main ( ) { int N = 12 ; if ( isHighlyCompositeNumber ( N ) ) cout << " Yes " ; else cout << " No " ; return 0 ; }
Pentacontahenagon Number | C ++ program for the above approach ; Function to find the N - th Pentacontahenagon Number ; Driver Code ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; int PentacontahenagonNum ( int N ) { return ( 49 * N * N - 47 * N ) / 2 ; } int main ( ) { int N = 3 ; cout << "3rd ▁ Pentacontahenagon ▁ Number ▁ is ▁ " << PentacontahenagonNum ( N ) ; return 0 ; }
Saint | C ++ implementation to check if N is a Saint - Exupery number ; Function to check if a number is a Saint - Exupery number ; Considering triplets in sorted order . The value of first element in sorted triplet can be at - most n / 3. ; The value of second element must be less than equal to n / 2 ; Driver Code ; Given Number N ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool isSaintExuperyNum ( int n ) { for ( int i = 1 ; i <= n / 3 ; i ++ ) { for ( int j = i + 1 ; j <= n / 2 ; j ++ ) { int k = n / i / j ; if ( i * i + j * j == k * k ) { if ( i * j * k == n ) return true ; ; } } } return false ; } int main ( ) { int N = 60 ; if ( isSaintExuperyNum ( N ) ) cout << " Yes " ; else cout << " No " ; return 0 ; }
Repdigit Numbers | C ++ implementation to check if a number is Repdigit ; Function to check if a number is a Repdigit number ; To store previous digit ( Assigning initial value which is less than any digit ) ; Traverse all digits from right to left and check if any digit is smaller than previous . ; Driver code
#include <iostream> NEW_LINE using namespace std ; bool isRepdigit ( int num , int b ) { int prev = -1 ; while ( num ) { int digit = num % b ; num /= b ; if ( prev != -1 && digit != prev ) return false ; prev = digit ; } return true ; } int main ( ) { int num = 2000 , base = 7 ; isRepdigit ( num , base ) ? cout << " Yes " : cout << " No " ; return 0 ; }
Enlightened Numbers | C ++ implementation of the above approach ; Function to check if N is a Composite Number ; Corner cases ; This is checked so that we can skip middle five numbers in below loop ; Function to return concatenation of distinct prime factors of a given number n ; Handle prime factor 2 explicitly so that can optimally handle other prime factors . ; 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 ; Function to check if a number is is an enlightened number ; Number should not be prime ; Converting N to string ; Function call ; Driver code
#include <iostream> NEW_LINE #include <math.h> NEW_LINE using namespace std ; bool isComposite ( int n ) { if ( n <= 3 ) return false ; if ( n % 2 == 0 n % 3 == 0 ) return true ; for ( int i = 5 ; i * i <= n ; i = i + 6 ) if ( n % i == 0 || n % ( i + 2 ) == 0 ) return true ; return false ; } int concatenatePrimeFactors ( int n ) { char concatenate ; if ( n % 2 == 0 ) { concatenate += char ( 2 ) ; while ( n % 2 == 0 ) n = n / 2 ; } for ( int i = 3 ; i <= sqrt ( n ) ; i = i + 2 ) { if ( n % i == 0 ) { concatenate += i ; while ( n % i == 0 ) n = n / i ; } } if ( n > 2 ) concatenate += n ; return concatenate ; } bool isEnlightened ( int N ) { if ( ! isComposite ( N ) ) return false ; char num = char ( N ) ; char prefixConc = concatenatePrimeFactors ( N ) ; return int ( prefixConc ) ; } int main ( ) { int n = 250 ; if ( isEnlightened ( n ) ) cout << " Yes " ; else cout << " No " ; }
Second Pentagonal 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 * ( 3 * n + 1 ) / 2 << endl ; } int main ( ) { int N = 4 ; findNthTerm ( N ) ; return 0 ; }
Idoneal Numbers | C ++ implementation for the above approach ; Function to check if number is an Idoneal numbers ; iterate for all triples pairs ( a , b , c ) ; if the condition is satisfied ; Driver Code ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool isIdoneal ( int n ) { for ( int a = 1 ; a <= n ; a ++ ) { for ( int b = a + 1 ; b <= n ; b ++ ) { for ( int c = b + 1 ; c <= n ; c ++ ) { if ( a * b + b * c + c * a == n ) return false ; } } } return true ; } int main ( ) { int N = 10 ; if ( isIdoneal ( N ) ) cout << " Yes " ; else cout << " No " ; return 0 ; }
Lynch | C ++ implementation for the above approach ; Function to check the divisibility of the number by its digit . ; If the digit divides the number then return true else return false . ; Function to check if all digits of n divide it or not ; Taking the digit of the number into digit var . ; Function to check if N has all distinct digits ; Create an array of size 10 and initialize all elements as false . This array is used to check if a digit is already seen or not . ; Traverse through all digits of given number ; Find the last digit ; If digit is already seen , return false ; Mark this digit as seen ; REmove the last digit from number ; Function to check Lynch - Bell numbers ; Driver Code ; Given Number N ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool checkDivisibility ( int n , int digit ) { return ( digit != 0 && n % digit == 0 ) ; } bool isAllDigitsDivide ( int n ) { int temp = n ; while ( temp > 0 ) { int digit = temp % 10 ; if ( ! ( checkDivisibility ( n , digit ) ) ) return false ; temp /= 10 ; } return true ; } bool isAllDigitsDistinct ( int n ) { bool arr [ 10 ] ; for ( int i = 0 ; i < 10 ; i ++ ) arr [ i ] = false ; while ( n > 0 ) { int digit = n % 10 ; if ( arr [ digit ] ) return false ; arr [ digit ] = true ; n = n / 10 ; } return true ; } bool isLynchBell ( int n ) { return isAllDigitsDivide ( n ) && isAllDigitsDistinct ( n ) ; } int main ( ) { int N = 12 ; if ( isLynchBell ( N ) ) cout << " Yes " ; else cout << " No " ; return 0 ; }
Repunit numbers | C ++ implementation to check if a number is Repunit Number ; Function to check if a number contains all the digits 0 , 1 , . . , ( b - 1 ) an equal number of times ; to store number of digits of n in base B ; to count frequency of digit 1 ; condition to check three or more 1 's and number of ones is equal to number of digits of n in base B ; Driver Code ; taking inputs ; function to check
#include <iostream> NEW_LINE #include <math.h> NEW_LINE using namespace std ; bool isRepunitNum ( int n , int b ) { int length = 0 ; int countOne = 0 ; while ( n != 0 ) { int r = n % b ; length ++ ; if ( r == 1 ) countOne ++ ; n = n / b ; } return countOne >= 3 && countOne == length ; } int main ( ) { int n = 31 ; int base = 2 ; if ( isRepunitNum ( n , base ) ) cout << " Yes " ; else cout << " NO " ; return 0 ; }
Gapful Numbers | C ++ program for the above approach ; Find the first digit ; Find total number of digits - 1 ; Find first digit ; Return first digit ; Find the last digit ; return the last digit ; A function to check Gapful numbers ; Return true if n is gapful number ; Driver Code ; Given Number ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; int firstDigit ( int n ) { int digits = ( int ) log10 ( n ) ; n = ( int ) ( n / pow ( 10 , digits ) ) ; return n ; } int lastDigit ( int n ) { return ( n % 10 ) ; } bool isGapful ( int n ) { int first_dig = firstDigit ( n ) ; int last_dig = lastDigit ( n ) ; int concatenation = first_dig * 10 + last_dig ; return ( n % concatenation == 0 ) ; } int main ( ) { int n = 108 ; if ( isGapful ( n ) ) cout << " Yes " ; else cout << " No " ; return 0 ; }
Economical Numbers | C ++ implementation to find Economical Numbers till n ; Array to store all prime less than and equal to MAX . ; Utility function for sieve of sundaram ; 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 ; 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 check if a number is a Economical number ; Count digits in original number ; Count all digits in prime factors of n pDigit is going to hold this value . ; Count powers of p in n ; If primes [ i ] is a prime factor , ; Count the power of prime factors ; Add its digits to pDigit . ; Add digits of power of prime factors to pDigit . ; If n != 1 then one prime factor still to be summed up ; ; If digits in prime factors is less than digits in original number then return true . Else return false . ; Driver code ; Finding all prime numbers before limit . These numbers are used to find prime factors .
#include <bits/stdc++.h> NEW_LINE using namespace std ; const int MAX = 10000 ; 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 = 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 ) ; } bool isEconomical ( int n ) { if ( n == 1 ) return false ; int original_no = n ; int sumDigits = 0 ; while ( original_no > 0 ) { sumDigits ++ ; original_no = original_no / 10 ; } int pDigit = 0 , count_exp = 0 , p ; for ( int i = 0 ; primes [ i ] <= n / 2 ; i ++ ) { while ( n % primes [ i ] == 0 ) { p = primes [ i ] ; n = n / p ; count_exp ++ ; } while ( p > 0 ) { pDigit ++ ; p = p / 10 ; } while ( count_exp > 1 ) { pDigit ++ ; count_exp = count_exp / 10 ; } } if ( n != 1 ) { while ( n > 0 ) { pDigit ++ ; n = n / 10 ; } } return ( pDigit < sumDigits ) ; } int main ( ) { sieveSundaram ( ) ; for ( int i = 1 ; i < 200 ; i ++ ) if ( isEconomical ( i ) ) cout << i << " ▁ " ; return 0 ; }
Check if all objects of type A and B can be placed on N shelves | C ++ implementation of the above approach ; Function to return if allocation is possible or not ; Stores the shelves needed for items of type - A and type - B ; Find number of shelves needed for items of type - A ; Fill A / K shelves fully by the items of type - A ; Otherwise ; Fill A / L shelves fully and add remaining to an extra shelf ; Find number of shelves needed for items of type - B ; Fill B / L shelves fully by the items of type - B ; Fill B / L shelves fully and add remaining to an an extra shelf ; Total shelves needed ; If required shelves exceed N ; Driver Program
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool isPossible ( int A , int B , int N , int K , int L ) { int needa , needb ; if ( A % K == 0 ) needa = A / K ; else needa = A / K + 1 ; if ( B % L == 0 ) needb = B / L ; else needb = B / L + 1 ; int total = needa + needb ; if ( total > N ) return false ; else return true ; } int main ( ) { int A = 3 , B = 3 , N = 3 ; int K = 4 , M = 2 ; if ( isPossible ( A , B , N , K , M ) ) cout << " YES " << endl ; else cout << " NO " << endl ; return 0 ; }
Minimise N such that sum of count of all factors upto N is greater than or equal to X | C ++ program for the above approach ; Array to store smallest prime factors of each no . ; Function to calculate smallest prime factor of N . ; marking spf [ j ] if it is not previously marked ; Array to store the count of factor for N ; Prefix array which contains the count of factors from 1 to N ; Function to count total factors from 1 to N ; Store total factors of i ; Stores total factors from 1 to i ; Function to search lowest X such that the given condition is satisfied ; Find mid ; Search in the right half ; Search in the left half ; Return the position after Binary Search ; Function to find the required sum ; Precompute smallest prime factor of each value ; Calculate count of total factors from 1 to N ; Binary search to find minimum N ; Driver Code ; Given Sum ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; #define MAX 1000050 NEW_LINE #define lli long int NEW_LINE lli spf [ MAX + 1 ] ; void calculate_SPF ( ) { for ( lli i = 0 ; i <= MAX ; i ++ ) spf [ i ] = i ; for ( lli i = 4 ; i <= MAX ; i += 2 ) spf [ i ] = 2 ; for ( lli i = 3 ; i * i <= MAX ; i ++ ) { if ( spf [ i ] == i ) { for ( int j = i * i ; j <= MAX ; j += i ) if ( spf [ j ] == j ) spf [ j ] = i ; } } } lli tfactor [ MAX + 1 ] ; lli pre [ MAX + 1 ] ; void CountTotalfactors ( ) { tfactor [ 1 ] = pre [ 1 ] = 1 ; for ( lli i = 2 ; i <= MAX ; i ++ ) { lli mspf = spf [ i ] ; lli prim = mspf ; lli temp = i ; lli cnt = 0 ; while ( temp % mspf == 0 ) { temp /= mspf ; cnt += 1 ; prim = prim * mspf ; } tfactor [ i ] = ( cnt + 1 ) * tfactor [ temp ] ; pre [ i ] = pre [ i - 1 ] + tfactor [ i ] ; } } lli BinarySearch ( lli X ) { lli start = 1 ; lli end = MAX - 1 ; while ( start < end ) { lli mid = ( start + end ) / 2 ; if ( pre [ mid ] == X ) return mid ; else if ( pre [ mid ] < X ) start = mid + 1 ; else end = mid ; } return start ; } void findSumOfCount ( int X ) { calculate_SPF ( ) ; CountTotalfactors ( ) ; cout << BinarySearch ( X ) << endl ; } int main ( ) { int X = 10 ; findSumOfCount ( X ) ; return 0 ; }
Check if the Matrix follows the given constraints or not | C ++ implementation of the above approach ; Stores true at prime indices ; Function to generate the prime numbers using Sieve of Eratosthenes ; If p is still true ; Mark all multiples of p ; Function returns sum of all elements of matrix ; Function to check if for all prime ( i + j ) , a [ i ] [ j ] is prime ; If index is prime ; Driver Code ; Check for both conditions
#include <bits/stdc++.h> NEW_LINE using namespace std ; vector < bool > prime ; void buildSieve ( int sum ) { prime = vector < bool > ( sum + 1 , true ) ; prime [ 0 ] = false ; prime [ 1 ] = false ; for ( int p = 2 ; p * p < ( sum + 1 ) ; p ++ ) { if ( prime [ p ] == true ) { for ( int i = p * 2 ; i < ( sum + 1 ) ; i += p ) prime [ i ] = false ; } } } int getSum ( int a [ 4 ] [ 5 ] ) { int s = 0 ; for ( int i = 0 ; i < 4 ; i ++ ) for ( int j = 0 ; j < 5 ; j ++ ) s += a [ i ] [ j ] ; return s ; } bool checkIndex ( int n , int m , int a [ 4 ] [ 5 ] ) { for ( int i = 0 ; i < n ; i ++ ) for ( int j = 0 ; j < m ; j ++ ) { if ( prime [ i + j ] && ! prime [ a [ i ] [ j ] ] ) { return false ; } } return true ; } int main ( ) { int n = 4 , m = 5 ; int a [ 4 ] [ 5 ] = { { 1 , 2 , 3 , 2 , 2 } , { 2 , 2 , 7 , 7 , 7 } , { 7 , 7 , 21 , 7 , 10 } , { 2 , 2 , 3 , 6 , 7 } } ; int sum = getSum ( a ) ; buildSieve ( sum ) ; if ( prime [ sum ] && checkIndex ( n , m , a ) ) { cout << " YES " << endl ; } else cout << " NO " << endl ; return 0 ; }
How to calculate the Easter date for a given year using Gauss ' Algorithm | C ++ program for the above approach ; Function calculates and prints easter date for given year Y ; All calculations done on the basis of Gauss Easter Algorithm ; A corner case , when D is 29 ; Another corner case , when D is 28 ; If days > 31 , move to April April = 4 th Month ; Otherwise , stay on March March = 3 rd Month ; Driver Code
#include <iostream> NEW_LINE #include <math.h> NEW_LINE using namespace std ; void gaussEaster ( int Y ) { float A , B , C , P , Q , M , N , D , E ; A = Y % 19 ; B = Y % 4 ; C = Y % 7 ; P = ( float ) floor ( Y / 100 ) ; Q = ( float ) floor ( ( 13 + 8 * P ) / 25 ) ; M = ( int ) ( 15 - Q + P - P / 4 ) % 30 ; N = ( int ) ( 4 + P - P / 4 ) % 7 ; D = ( int ) ( 19 * A + M ) % 30 ; E = ( int ) ( 2 * B + 4 * C + 6 * D + N ) % 7 ; int days = ( int ) ( 22 + D + E ) ; if ( ( D == 29 ) && ( E == 6 ) ) { cout << Y << " - 04-19" ; return ; } else if ( ( D == 28 ) && ( E == 6 ) ) { cout << Y << " - 04-18" ; return ; } else { if ( days > 31 ) { cout << Y << " - 04 - " << ( days - 31 ) ; return ; } else { cout << Y << " - 03 - " << days ; return ; } } } int main ( ) { int Y = 2020 ; gaussEaster ( Y ) ; return 0 ; }
Min steps to convert N | C ++ program for the above problem ; adjacency list for numbers till 100001 ; visited array ; to store distance of every vertex from A ; function to check if number is a prime ; function to check if numbers differ by only a single - digit ; check the last digit of both numbers and increase count if different ; generate all N digit primes ; for every prime number i check if an edge can be made . ; for every prime number i check if an edge can be made from i to j . ; if edge is possible then insert in the adjacency list ; function to count distance ; if unvisited push onto queue and mark visited as 1 and add the distance of curr + 1. ; Driver code ; Call bfs traversal with root as node A ; Indicates not possible
#include <bits/stdc++.h> NEW_LINE using namespace std ; #define ll long long NEW_LINE #define mod 1000000007 NEW_LINE #define pb push_back NEW_LINE #define mod 1000000007 NEW_LINE #define vi vector<int> NEW_LINE vi lis [ 100001 ] ; vi primes ; int vis [ 100001 ] ; int dis [ 100001 ] ; bool isPrime ( int n ) { for ( int i = 2 ; i * i <= n ; i ++ ) { if ( n % i == 0 ) return false ; } return true ; } bool valid ( int a , int b ) { int c = 0 ; while ( a ) { if ( ( a % 10 ) != ( b % 10 ) ) { c ++ ; } a = a / 10 ; b = b / 10 ; } if ( c == 1 ) { return true ; } else { return false ; } } void makePrimes ( int N ) { int i , j ; int L = pow ( 10 , N - 1 ) ; int R = pow ( 10 , N ) - 1 ; for ( int i = L ; i <= R ; i ++ ) { if ( isPrime ( i ) ) { primes . pb ( i ) ; } } for ( i = 0 ; i < primes . size ( ) ; i ++ ) { for ( j = i + 1 ; j < primes . size ( ) ; j ++ ) { int a = primes [ i ] ; int b = primes [ j ] ; if ( valid ( a , b ) ) { lis [ a ] . pb ( b ) ; lis [ b ] . pb ( a ) ; } } } } void bfs ( int src ) { queue < int > q ; q . push ( src ) ; vis [ src ] = 1 ; dis [ src ] = 0 ; while ( ! q . empty ( ) ) { int curr = q . front ( ) ; q . pop ( ) ; for ( int x : lis [ curr ] ) { if ( vis [ x ] == 0 ) { vis [ x ] = 1 ; q . push ( x ) ; dis [ x ] = dis [ curr ] + 1 ; } } } } int main ( ) { int N = 4 ; makePrimes ( N ) ; int A = 1033 , B = 8179 ; bfs ( A ) ; if ( dis [ B ] == -1 ) cout << " - 1" << endl ; else cout << dis [ B ] << endl ; return 0 ; }