text
stringlengths 17
4.49k
| code
stringlengths 49
5.46k
|
---|---|
Form smallest number using indices of numbers chosen from Array with sum less than S | C ++ implementation to find minimum number which have a maximum length ; Function to find the minimum number which have maximum length ; Find Maximum length of number ; Find minimum number WHich have maximum length ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; string max_number ( int arr [ ] , int sum ) { int frac [ 9 ] ; int maxi = INT_MIN ; string ans ; int pos ; for ( int i = 0 ; i < 9 ; i ++ ) { frac [ i ] = sum / arr [ i ] ; if ( frac [ i ] > maxi ) { pos = i ; maxi = frac [ i ] ; } } ans . insert ( 0 , string ( maxi , ( pos + 1 ) + '0' ) ) ; sum -= maxi * arr [ pos ] ; for ( int i = 0 ; i < maxi ; i ++ ) { for ( int j = 1 ; j <= 9 ; j ++ ) { if ( sum + arr [ pos ] - arr [ j - 1 ] >= 0 ) { ans [ i ] = ( j + '0' ) ; sum += arr [ pos ] - arr [ j - 1 ] ; break ; } } } if ( maxi == 0 ) { return 0 ; } else { return ans ; } } int main ( ) { int arr [ 9 ] = { 3 , 4 , 2 , 4 , 6 , 5 , 4 , 2 , 3 } ; int s = 13 ; cout << max_number ( arr , s ) ; return 0 ; } |
Check if given intervals can be made non | C ++ implementation to check if the intervals can be non - overlapping by adding or subtracting X to each interval ; Function to check if two intervals overlap with each other ; Condition to check if the intervals overlap ; Function to check if there is a existing overlapping intervals ; Path compression ; Union of two intervals Returns True if there is a overlapping with the same another interval ; Both have same another overlapping interval ; Function to check if the intervals can be added by X to form non - overlapping intervals ; If the intervals overlaps we will union them ; There is no cycle ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; bool checkOverlapping ( vector < int > a , vector < int > b ) { if ( a [ 0 ] < b [ 0 ] ) { a . swap ( b ) ; } if ( b [ 0 ] <= a [ 0 ] <= b [ 1 ] ) return true ; return false ; } int find ( int a [ ] , int i ) { if ( a [ i ] == i ) return i ; a [ i ] = find ( a , a [ i ] ) ; return a [ i ] ; } bool Union ( int a [ ] , int x , int y ) { int xs = find ( a , x ) ; int ys = find ( a , y ) ; if ( xs == ys ) { return true ; } a [ ys ] = xs ; return false ; } bool checkNonOverlapping ( vector < vector < int > > arr , int n ) { int dsu [ n + 1 ] ; for ( int i = 0 ; i < n + 1 ; i ++ ) dsu [ i ] = i ; for ( int i = 0 ; i < n ; i ++ ) { for ( int j = i + 1 ; j < n ; j ++ ) { if ( checkOverlapping ( arr [ i ] , arr [ j ] ) ) { if ( Union ( dsu , i , j ) ) { return false ; } } } } return true ; } int main ( ) { vector < vector < int > > arr = { { 1 , 4 } , { 2 , 2 } , { 2 , 3 } } ; int n = arr . size ( ) ; if ( checkNonOverlapping ( arr , n ) ) { cout << " YES " << endl ; } else { cout << " NO " << endl ; } return 0 ; } |
Number formed after K times repeated addition of smallest divisor of N | C ++ program to find the Kth number formed after repeated addition of smallest divisor of N ; If N is even ; If N is odd ; Add smallest divisor to N ; Updated N is even ; Driver code | #include <bits/stdc++.h> NEW_LINE #include <cmath> NEW_LINE using namespace std ; void FindValue ( int N , int K ) { if ( N % 2 == 0 ) { N = N + 2 * K ; } else { int i ; for ( i = 2 ; i < sqrt ( N ) + 1 ; i ++ ) { if ( N % i == 0 ) break ; } N = N + i ; N = N + 2 * ( K - 1 ) ; } cout << N << endl ; } int main ( ) { int N = 9 ; int K = 4 ; FindValue ( N , K ) ; } |
Find last digit in factorial | C ++ program to find last digit in factorial n . ; Explicitly handle all numbers less than or equal to 4 ; For all numbers greater than 4 the last digit is 0 ; Driver code | #include <iostream> NEW_LINE using namespace std ; int lastDigitFactorial ( unsigned int n ) { if ( n == 0 ) return 1 ; else if ( n <= 2 ) return n ; else if ( n == 3 ) return 6 ; else if ( n == 4 ) return 4 ; else return 0 ; } int main ( ) { cout << lastDigitFactorial ( 6 ) ; return 0 ; } |
Program to convert Hexa | C ++ implementation to convert the given HexaDecimal number to its equivalent BCD . ; Function to convert HexaDecimal to its BCD ; Iterating through the digits ; check whether s [ i ] is a character or a integer between 0 to 9 and compute its equivalent BCD ; Driver Code ; Function Call | #include <bits/stdc++.h> NEW_LINE using namespace std ; void HexaDecimaltoBCD ( string s ) { int len = s . length ( ) , check = 0 ; int num = 0 , sum = 0 , mul = 1 ; for ( int i = 0 ; i <= len - 1 ; i ++ ) { if ( s [ i ] >= 47 && s [ i ] <= 52 ) cout << bitset < 4 > ( s [ i ] ) << " β " ; else cout << bitset < 4 > ( s [ i ] - 55 ) << " β " ; } } int main ( ) { string s = "11F " ; HexaDecimaltoBCD ( s ) ; return 0 ; } |
Find the sum of the first Nth Heptadecagonal Number | C ++ program to find the sum of the first N heptadecagonal numbers ; Function to find the N - th heptadecagonal number ; Formula to calculate nth heptadecagonal number ; Function to find the sum of the first N heptadecagonal numbers ; Variable to store the sum ; Iterating from 1 to N ; Finding the sum ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int heptadecagonal_num ( int n ) { return ( ( 15 * n * n ) - 13 * n ) / 2 ; } int sum_heptadecagonal_num ( int n ) { int summ = 0 ; for ( int i = 1 ; i < n + 1 ; i ++ ) { summ += heptadecagonal_num ( i ) ; } return summ ; } int main ( ) { int n = 5 ; cout << sum_heptadecagonal_num ( n ) ; } |
Program to check if N is a Centered Pentagonal Number or not | C ++ program for the above approach ; Function to check if number N is a Centered pentagonal number ; Condition to check if N is a Centered pentagonal number ; Driver Code ; Given Number ; Function call | #include <bits/stdc++.h> NEW_LINE using namespace std ; bool isCenteredpentagonal ( int N ) { float n = ( 5 + sqrt ( 40 * N - 15 ) ) / 10 ; return ( n - ( int ) n ) == 0 ; } int main ( ) { int N = 6 ; if ( isCenteredpentagonal ( N ) ) { cout << " Yes " ; } else { cout << " No " ; } return 0 ; } |
Program to check if N is a Dodecagonal Number | C ++ program for the above approach ; Function to check if number N is a dodecagonal number or not ; Condition to check if the N is a dodecagonal number ; Driver Code ; Given Number ; Function call | #include <bits/stdc++.h> NEW_LINE using namespace std ; bool isdodecagonal ( int N ) { float n = ( 4 + sqrt ( 20 * N + 16 ) ) / 10 ; return ( n - ( int ) n ) == 0 ; } int main ( ) { int N = 12 ; if ( isdodecagonal ( N ) ) { cout << " Yes " ; } else { cout << " No " ; } return 0 ; } |
Logarithm tricks for Competitive Programming | C ++ implementation to find the previous and next power of K ; Function to return the highest power of k less than or equal to n ; Function to return the smallest power of k greater than or equal to n ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int prevPowerofK ( int n , int k ) { int p = ( int ) ( log ( n ) / log ( k ) ) ; return ( int ) pow ( k , p ) ; } int nextPowerOfK ( int n , int k ) { return prevPowerofK ( n , k ) * k ; } int main ( ) { int N = 7 ; int K = 2 ; cout << prevPowerofK ( N , K ) << " β " ; cout << nextPowerOfK ( N , K ) << endl ; return 0 ; } |
Sum of all composite numbers lying in the range [ L , R ] for Q queries | C ++ implementation to find the sum of all composite numbers in the given range ; Prefix array to precompute the sum of all composite numbers ; Function that return number num if num is composite else return 0 ; Corner cases ; This is checked so that we can skip middle five numbers in below loop ; Function to precompute the sum of all Composite numbers upto 10 ^ 5 ; isComposite ( ) return the number i if i is Composite else return 0 ; Function to print the sum for each query ; Function to print sum of all Composite numbers between [ L , R ] ; Function that pre computes the sum of all Composite numbers ; Iterate over all Queries to print the sum ; Driver code ; Queries ; Function that print the the sum of all composite number in Range [ L , R ] | #include <bits/stdc++.h> NEW_LINE using namespace std ; long long pref [ 100001 ] ; int isComposite ( int n ) { if ( n <= 1 ) return 0 ; if ( n <= 3 ) return 0 ; if ( n % 2 == 0 n % 3 == 0 ) return n ; for ( int i = 5 ; i * i <= n ; i = i + 6 ) if ( n % i == 0 || n % ( i + 2 ) == 0 ) return n ; return 0 ; } void preCompute ( ) { for ( int i = 1 ; i <= 100000 ; ++ i ) { pref [ i ] = pref [ i - 1 ] + isComposite ( i ) ; } } void printSum ( int L , int R ) { cout << pref [ R ] - pref [ L - 1 ] << endl ; } void printSumComposite ( int arr [ ] [ 2 ] , int Q ) { preCompute ( ) ; for ( int i = 0 ; i < Q ; i ++ ) { printSum ( arr [ i ] [ 0 ] , arr [ i ] [ 1 ] ) ; } } int main ( ) { int Q = 2 ; int arr [ ] [ 2 ] = { { 10 , 13 } , { 12 , 21 } } ; printSumComposite ( arr , Q ) ; return 0 ; } |
Probability of getting a perfect square when a random number is chosen in a given range | C ++ implementation to find the probability of getting a perfect square number ; Function to return the probability of getting a perfect square number in a range ; Count of perfect squares ; Total numbers in range l to r ; Calculating probability ; Driver Code ; Function Call | #include <bits/stdc++.h> NEW_LINE using namespace std ; float findProb ( int l , int r ) { float countOfPS = floor ( sqrt ( r ) ) - ceil ( sqrt ( l ) ) + 1 ; float total = r - l + 1 ; float prob = ( float ) countOfPS / ( float ) total ; return prob ; } int main ( ) { int L = 16 , R = 25 ; cout << findProb ( L , R ) ; return 0 ; } |
Check whether two strings can be made equal by increasing prefixes | C ++ implementation of above approach ; check whether the first string can be converted to the second string by increasing the ASCII value of prefix string of first string ; length of two strings ; If lengths are not equal ; store the difference of ASCII values ; difference of first element ; traverse through the string ; the ASCII value of the second string should be greater than or equal to first string , if it is violated return false . ; store the difference of ASCII values ; the difference of ASCII values should be in descending order ; if the difference array is not in descending order ; if all the ASCII values of characters of first string is less than or equal to the second string and the difference array is in descending order , return true ; Driver code ; create two strings ; check whether the first string can be converted to the second string | #include <iostream> NEW_LINE using namespace std ; bool find ( string s1 , string s2 ) { int len = s1 . length ( ) , len_1 = s2 . length ( ) ; if ( len != len_1 ) return false ; int d [ len ] = { 0 } ; d [ 0 ] = s2 [ 0 ] - s1 [ 0 ] ; for ( int i = 1 ; i < len ; i ++ ) { if ( s1 [ i ] > s2 [ i ] ) return false ; else { d [ i ] = s2 [ i ] - s1 [ i ] ; } } for ( int i = 0 ; i < len - 1 ; i ++ ) { if ( d [ i ] < d [ i + 1 ] ) return false ; } return true ; } int main ( ) { string s1 = " abcd " , s2 = " bcdd " ; if ( find ( s1 , s2 ) ) cout << " Yes " ; else cout << " No " ; return 0 ; } |
Count of groups having largest size while grouping according to sum of its digits | C ++ implementation to Count the number of groups having the largest size where groups are according to the sum of its digits ; function to return sum of digits of i ; Create the dictionary of unique sum ; dictionary that contain unique sum count ; calculate the sum of its digits ; function to find the largest size of group ; count of largest size group ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int sumDigits ( int n ) { int sum = 0 ; while ( n ) { sum += n % 10 ; n /= 10 ; } return sum ; } map < int , int > constDict ( int n ) { map < int , int > d ; for ( int i = 1 ; i < n + 1 ; ++ i ) { int sum1 = sumDigits ( i ) ; if ( d . find ( sum1 ) == d . end ( ) ) d [ sum1 ] = 1 ; else d [ sum1 ] += 1 ; } return d ; } int countLargest ( int n ) { map < int , int > d = constDict ( n ) ; int size = 0 ; int count = 0 ; for ( auto it = d . begin ( ) ; it != d . end ( ) ; ++ it ) { int k = it -> first ; int val = it -> second ; if ( val > size ) { size = val ; count = 1 ; } else if ( val == size ) count += 1 ; } return count ; } int main ( ) { int n = 13 ; int group = countLargest ( n ) ; cout << group << endl ; return 0 ; } |
Find the length of factorial of a number in any given base | A optimised program to find the number of digits in a factorial in base b ; Returns the number of digits present in n ! in base b Since the result can be large long long is used as return type ; factorial of - ve number doesn 't exists ; base case ; Use Kamenetsky formula to calculate the number of digits ; Driver Code ; calling findDigits ( Number , Base ) | #include <bits/stdc++.h> NEW_LINE using namespace std ; long long findDigits ( int n , int b ) { if ( n < 0 ) return 0 ; if ( n <= 1 ) return 1 ; double x = ( ( n * log10 ( n / M_E ) + log10 ( 2 * M_PI * n ) / 2.0 ) ) / ( log10 ( b ) ) ; return floor ( x ) + 1 ; } int main ( ) { cout << findDigits ( 4 , 16 ) << endl ; cout << findDigits ( 5 , 8 ) << endl ; cout << findDigits ( 12 , 16 ) << endl ; cout << findDigits ( 19 , 13 ) << endl ; return 0 ; } |
Sum of all Non | C ++ implementation to find the sum of all non - fibonacci numbers in a range from L to R ; Array to precompute the sum of non - fibonacci numbers ; Function to find if a number is a perfect square ; Function that returns N if N is non - fibonacci number ; N is Fibinacci if one of 5 * n * n + 4 or 5 * n * n - 4 or both are perferct square ; Function to precompute sum of non - fibonacci Numbers ; Function to find the sum of all non - fibonacci numbers in a range ; Driver Code ; Pre - computation ; Loop to find the sum for each query | #include <bits/stdc++.h> NEW_LINE #define ll int NEW_LINE using namespace std ; long long pref [ 100010 ] ; bool isPerfectSquare ( int x ) { int s = sqrt ( x ) ; return ( s * s == x ) ; } int isNonFibonacci ( int n ) { if ( isPerfectSquare ( 5 * n * n + 4 ) || isPerfectSquare ( 5 * n * n - 4 ) ) return 0 ; else return n ; } void compute ( ) { for ( int i = 1 ; i <= 100000 ; ++ i ) { pref [ i ] = pref [ i - 1 ] + isNonFibonacci ( i ) ; } } void printSum ( int L , int R ) { int sum = pref [ R ] - pref [ L - 1 ] ; cout << sum << " β " ; } int main ( ) { compute ( ) ; int Q = 2 ; int arr [ ] [ 2 ] = { { 1 , 5 } , { 6 , 10 } } ; for ( int i = 0 ; i < Q ; i ++ ) { printSum ( arr [ i ] [ 0 ] , arr [ i ] [ 1 ] ) ; } return 0 ; } |
Count twin prime pairs in an Array | C ++ program to count Twin Prime pairs in array ; A utility function to check if the number n is prime or not ; Base Cases ; Check to skip middle five numbers in below loop ; If n is divisible by i and i + 2 then it is not prime ; A utility function that check if n1 and n2 are Twin Primes or not ; Function to find Twin Prime pairs from the given array ; Iterate through all pairs ; Increment count if twin prime pair ; Driver 's code ; Function call to find Twin Primes pair | #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 += 6 ) { if ( n % i == 0 || n % ( i + 2 ) == 0 ) { return false ; } } return true ; } bool twinPrime ( int n1 , int n2 ) { return ( isPrime ( n1 ) && isPrime ( n2 ) && abs ( n1 - n2 ) == 2 ) ; } int countTwinPairs ( int arr [ ] , int n ) { int count = 0 ; for ( int i = 0 ; i < n ; i ++ ) { for ( int j = i + 1 ; j < n ; j ++ ) { if ( twinPrime ( arr [ i ] , arr [ j ] ) ) { count ++ ; } } } return count ; } int main ( ) { int arr [ ] = { 2 , 3 , 5 , 11 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << countTwinPairs ( arr , n ) ; return 0 ; } |
Fill the missing numbers in the array of N natural numbers such that arr [ i ] not equal to i | C ++ implementation of above approach ; Function to fill the position with arr [ i ] = 0 ; Inserting all elements in missing [ ] set from 1 to N ; Inserting unfilled positions ; Removing allocated_elements ; Loop for filling the positions with arr [ i ] != i ; Checking for any arr [ i ] = i ; Finding the suitable position in the array to swap with found i for which arr [ i ] = i ; Checking if the position is present in unfilled_position ; Swapping arr [ i ] & arr [ pos ] ( arr [ pos ] = pos ) ; Function to Print the array ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; void printArray ( int [ ] , int ) ; void solve ( int arr [ ] , int n ) { set < int > unfilled_indices ; set < int > missing ; for ( int i = 1 ; i < n ; i ++ ) missing . insert ( i ) ; for ( int i = 1 ; i < n ; i ++ ) { if ( arr [ i ] == 0 ) unfilled_indices . insert ( i ) ; else { auto it = missing . find ( arr [ i ] ) ; missing . erase ( it ) ; } } auto it2 = missing . end ( ) ; it2 -- ; for ( auto it = unfilled_indices . begin ( ) ; it != unfilled_indices . end ( ) ; it ++ , it2 -- ) { arr [ * it ] = * it2 ; } int pos = 0 ; for ( int i = 1 ; i < n ; i ++ ) { if ( arr [ i ] == i ) { pos = i ; } } int x ; if ( pos != 0 ) { for ( int i = 1 ; i < n ; i ++ ) { if ( pos != i ) { if ( unfilled_indices . find ( i ) != unfilled_indices . end ( ) ) { x = arr [ i ] ; arr [ i ] = pos ; arr [ pos ] = x ; break ; } } } } printArray ( arr , n ) ; } void printArray ( int arr [ ] , int n ) { for ( int i = 1 ; i < n ; i ++ ) cout << arr [ i ] << " β " ; } int main ( ) { int arr [ ] = { 0 , 7 , 4 , 0 , 3 , 0 , 5 , 1 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; solve ( arr , n ) ; return 0 ; } |
Find minimum value of y for the given x values in Q queries from all the given set of lines | C ++ implementation of the above approach ; Sort the line in decreasing order of their slopes ; If slopes arent equal ; If the slopes are equal ; Checks if line L3 or L1 is better than L2 Intersection of Line 1 and Line 2 has x - coordinate ( b1 - b2 ) / ( m2 - m1 ) Similarly for Line 1 and Line 3 has x - coordinate ( b1 - b3 ) / ( m3 - m1 ) Cross multiplication will give the below result ; To store the lines ; Add the line to the set of lines ; To check if after adding the new line whether old lines are losing significance or not ; Add the present line ; Function to return the y coordinate of the specified line for the given coordinate ; Function to Return the minimum value of y for the given x coordinate ; if there is no lines ; Binary search ; Driver code ; Sort the lines ; Add the lines ; For each query in Q | #include <bits/stdc++.h> NEW_LINE using namespace std ; struct Line { int m , c ; public : bool operator< ( Line l ) { if ( m != l . m ) return m > l . m ; else return c > l . c ; } bool check ( Line L1 , Line L2 , Line L3 ) { return ( L3 . c - L1 . c ) * ( L1 . m - L2 . m ) < ( L2 . c - L1 . c ) * ( L1 . m - L3 . m ) ; } } ; struct Convex_HULL_Trick { vector < Line > l ; void add ( Line newLine ) { int n = l . size ( ) ; while ( n >= 2 && newLine . check ( l [ n - 2 ] , l [ n - 1 ] , newLine ) ) { n -- ; } l . resize ( n ) ; l = new Line [ n ] ; l . push_back ( newLine ) ; } int value ( int in , int x ) { return l [ in ] . m * x + l [ in ] . c ; } int minQuery ( int x ) { if ( l . empty ( ) ) return INT_MAX ; int low = 0 , high = ( int ) l . size ( ) - 2 ; while ( low <= high ) { int mid = ( low + high ) / 2 ; if ( value ( mid , x ) > value ( mid + 1 , x ) ) low = mid + 1 ; else high = mid - 1 ; } return value ( low , x ) ; } } ; int main ( ) { Line lines [ ] = { { 1 , 1 } , { 0 , 0 } , { -3 , 3 } } ; int Q [ ] = { -2 , 2 , 0 } ; int n = 3 , q = 3 ; Convex_HULL_Trick cht ; sort ( lines , lines + n ) ; for ( int i = 0 ; i < n ; i ++ ) cht . add ( lines [ i ] ) ; for ( int i = 0 ; i < q ; i ++ ) { int x = Q [ i ] ; cout << cht . minQuery ( x ) << endl ; } return 0 ; } |
Find Kth number from sorted array formed by multiplying any two numbers in the array | C ++ implementation to find the Kth number in the list formed from product of any two numbers in the array and sorting them ; Function to find number of pairs ; Negative and Negative ; Add Possible Pairs ; Positive and Positive ; Add Possible pairs ; Negative and Positive ; Add Possible pairs ; Function to find the kth element in the list ; Separate Positive and Negative elements ; Sort the Elements ; Binary search ; Return the required answer ; Driver code ; Function call | #include <bits/stdc++.h> NEW_LINE using namespace std ; bool check ( long long x , vector < int > & pos , vector < int > & neg , int k ) { long long pairs = 0 ; int p = neg . size ( ) - 1 ; int nn = neg . size ( ) - 1 ; int pp = pos . size ( ) - 1 ; for ( int i = 0 ; i < neg . size ( ) ; i ++ ) { while ( p >= 0 and neg [ i ] * neg [ p ] <= x ) p -- ; pairs += min ( nn - p , nn - i ) ; } p = 0 ; for ( int i = pos . size ( ) - 1 ; i >= 0 ; i -- ) { while ( p < pos . size ( ) and pos [ i ] * pos [ p ] <= x ) p ++ ; pairs += min ( p , i ) ; } p = pos . size ( ) - 1 ; for ( int i = neg . size ( ) - 1 ; i >= 0 ; i -- ) { while ( p >= 0 and neg [ i ] * pos [ p ] <= x ) p -- ; pairs += pp - p ; } return ( pairs >= k ) ; } long long kth_element ( int a [ ] , int n , int k ) { vector < int > pos , neg ; for ( int i = 0 ; i < n ; i ++ ) { if ( a [ i ] >= 0 ) pos . push_back ( a [ i ] ) ; else neg . push_back ( a [ i ] ) ; } sort ( pos . begin ( ) , pos . end ( ) ) ; sort ( neg . begin ( ) , neg . end ( ) ) ; long long l = -1e18 , ans = 0 , r = 1e18 ; while ( l <= r ) { long long mid = ( l + r ) >> 1 ; if ( check ( mid , pos , neg , k ) ) { ans = mid ; r = mid - 1 ; } else l = mid + 1 ; } return ans ; } int main ( ) { int a [ ] = { -4 , -2 , 3 , 3 } , k = 3 ; int n = sizeof ( a ) / sizeof ( a [ 0 ] ) ; cout << kth_element ( a , n , k ) ; return 0 ; } |
Find root of a number using Newton 's method | C ++ implementation of the approach ; Function to return the square root of a number using Newtons method ; Assuming the sqrt of n as n only ; The closed guess will be stored in the root ; To count the number of iterations ; Calculate more closed x ; Check for closeness ; Update root ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; double squareRoot ( double n , float l ) { double x = n ; double root ; int count = 0 ; while ( 1 ) { count ++ ; root = 0.5 * ( x + ( n / x ) ) ; if ( abs ( root - x ) < l ) break ; x = root ; } return root ; } int main ( ) { double n = 327 ; float l = 0.00001 ; cout << squareRoot ( n , l ) ; return 0 ; } |
Count the occurrence of Nth term in first N terms of Van Eck 's sequence | C ++ program to count the occurrence of nth term in first n terms of Van Eck 's sequence ; Utility function to compute Van Eck 's sequence ; Initialize sequence array ; Loop to generate sequence ; Check if sequence [ i ] has occured previously or is new to sequence ; If occurrence found then the next term will be how far back this last term occured previously ; Utility function to count the occurrence of nth term in first n terms of the sequence ; Get nth term of the sequence ; Count the occurrence of nth term in first n terms of the sequence ; Return count ; Driver code ; Pre - compute Van Eck 's sequence ; Print count of the occurrence of nth term in first n terms of the sequence ; Print count of the occurrence of nth term in first n terms of the sequence | #include <bits/stdc++.h> NEW_LINE using namespace std ; #define MAX 100000 NEW_LINE int sequence [ MAX + 1 ] ; void vanEckSequence ( ) { for ( int i = 0 ; i < MAX ; i ++ ) { sequence [ i ] = 0 ; } for ( int i = 0 ; i < MAX ; i ++ ) { for ( int j = i - 1 ; j >= 0 ; j -- ) { if ( sequence [ j ] == sequence [ i ] ) { sequence [ i + 1 ] = i - j ; break ; } } } } int getCount ( int n ) { int nthTerm = sequence [ n - 1 ] ; int count = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( sequence [ i ] == nthTerm ) count ++ ; } return count ; } int main ( ) { vanEckSequence ( ) ; int n = 5 ; cout << getCount ( n ) << endl ; n = 11 ; cout << getCount ( n ) << endl ; return 0 ; } |
Count the occurrence of Nth term in first N terms of Van Eck 's sequence | C ++ program to count the occurrence of nth term in first n terms of Van Eck 's sequence ; Utility function to compute Van Eck 's sequence ; Initialize sequence array ; Loop to generate sequence ; Check if sequence [ i ] has occured previously or is new to sequence ; If occurrence found then the next term will be how far back this last term occured previously ; Utility function to count the occurrence of nth term in first n terms of the sequence ; Initialize count as 1 ; Increment count if ( i + 1 ) th term is non - zero ; Previous occurrence of sequence [ i ] will be it ( i - sequence [ i + 1 ] ) th position ; Return the count of occurrence ; Driver code ; Pre - compute Van Eck 's sequence ; Print count of the occurrence of nth term in first n terms of the sequence ; Print count of the occurrence of nth term in first n terms of the sequence | #include <bits/stdc++.h> NEW_LINE using namespace std ; #define MAX 100000 NEW_LINE int sequence [ MAX + 1 ] ; void vanEckSequence ( ) { for ( int i = 0 ; i < MAX ; i ++ ) { sequence [ i ] = 0 ; } for ( int i = 0 ; i < MAX ; i ++ ) { for ( int j = i - 1 ; j >= 0 ; j -- ) { if ( sequence [ j ] == sequence [ i ] ) { sequence [ i + 1 ] = i - j ; break ; } } } } int getCount ( int n ) { int count = 1 ; int i = n - 1 ; while ( sequence [ i + 1 ] != 0 ) { count ++ ; i = i - sequence [ i + 1 ] ; } return count ; } int main ( ) { vanEckSequence ( ) ; int n = 5 ; cout << getCount ( n ) << endl ; n = 11 ; cout << getCount ( n ) << endl ; return 0 ; } |
Program to find the time remaining for the day to complete | Function to find the remaining time ; Formula for total remaining minutes = 1440 - 60 h - m ; Remaining hours ; Remaining minutes ; Driver code ; Current time ; Get the remaining time | #include <bits/stdc++.h> NEW_LINE using namespace std ; void remainingTime ( int h , int m ) { int totalMin , hoursRemaining , minRemaining ; totalMin = 1440 - 60 * h - m ; hoursRemaining = totalMin / 60 ; minRemaining = totalMin % 60 ; cout << hoursRemaining << " : : " << minRemaining << endl ; } int main ( ) { int h = 0 , m = 1 ; remainingTime ( h , m ) ; return 0 ; } |
Goldbach 's Weak Conjecture for Odd numbers | C ++ implementation of the approach ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; void check ( int n ) { if ( n % 2 == 1 && n > 5 ) cout << " Yes STRNEWLINE " ; else cout << " No STRNEWLINE " ; } int main ( ) { int a = 3 ; int b = 7 ; check ( a ) ; check ( b ) ; return 0 ; } |
Number of ways to reach ( X , Y ) in a matrix starting from the origin | C ++ implementation of the approach ; To store the factorial and factorial mod inverse of the numbers ; Function to find ( a ^ m1 ) % mod ; Function to find the factorial of all the numbers ; Function to find the factorial modinverse of all the numbers ; Function to return nCr ; Function to return the number of ways to reach ( X , Y ) in a matrix with the given moves starting from the origin ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; #define N 1000005 NEW_LINE #define mod (int)(1e9 + 7) NEW_LINE int factorial [ N ] , modinverse [ N ] ; int power ( int a , int m1 ) { if ( m1 == 0 ) return 1 ; else if ( m1 == 1 ) return a ; else if ( m1 == 2 ) return ( 1LL * a * a ) % mod ; else if ( m1 & 1 ) return ( 1LL * a * power ( power ( a , m1 / 2 ) , 2 ) ) % mod ; else return power ( power ( a , m1 / 2 ) , 2 ) % mod ; } void factorialfun ( ) { factorial [ 0 ] = 1 ; for ( int i = 1 ; i < N ; i ++ ) factorial [ i ] = ( 1LL * factorial [ i - 1 ] * i ) % mod ; } void modinversefun ( ) { modinverse [ N - 1 ] = power ( factorial [ N - 1 ] , mod - 2 ) % mod ; for ( int i = N - 2 ; i >= 0 ; i -- ) modinverse [ i ] = ( 1LL * modinverse [ i + 1 ] * ( i + 1 ) ) % mod ; } int binomial ( int n , int r ) { if ( r > n ) return 0 ; int a = ( 1LL * factorial [ n ] * modinverse [ n - r ] ) % mod ; a = ( 1LL * a * modinverse [ r ] ) % mod ; return a ; } int ways ( int x , int y ) { factorialfun ( ) ; modinversefun ( ) ; if ( ( 2 * x - y ) % 3 == 0 && ( 2 * y - x ) % 3 == 0 ) { int m = ( 2 * x - y ) / 3 ; int n = ( 2 * y - x ) / 3 ; return binomial ( n + m , n ) ; } return 0 ; } System . out . println ( n + m + " β " + n ) ; int main ( ) { int x = 3 , y = 3 ; cout << ways ( x , y ) ; return 0 ; } |
Find Nth even length palindromic number formed using digits X and Y | C ++ program to find nth even palindromic number of only even length composing of 4 ' s β and β 5' s . ; Utility function to compute n 'th palindrome number ; Calculate the length from above formula as discussed above ; Calculate rank for length L ; Mask to check if i 't bit is set or not ; If bit is set append '5' else append '4' ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; string solve ( int n , char x , char y ) { int length = ceil ( log2 ( n + 2 ) ) - 1 ; int rank = n - ( 1 << length ) + 1 ; string left = " " , right = " " ; for ( int i = length - 1 ; i >= 0 ; i -- ) { int mask = 1 << i ; bool bit = mask & rank ; if ( bit ) { left += y ; right += y ; } else { left += x ; right += x ; } } reverse ( right . begin ( ) , right . end ( ) ) ; return left + right ; } int main ( ) { int n = 23 ; char x = '4' , y = '5' ; string ans = solve ( n , x , y ) ; cout << ans << ' ' ; return 0 ; } |
Maximum of all the integers in the given level of Pascal triangle | C ++ implementation of the approach ; Function for the binomial coefficient ; Calculate value of Binomial Coefficient in bottom up manner ; Base Cases ; Calculate value using previously stored values ; Function to return the maximum value in the nth level of the Pascal 's triangle ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int binomialCoeff ( int n , int k ) { int C [ n + 1 ] [ k + 1 ] ; int i , j ; for ( i = 0 ; i <= n ; i ++ ) { for ( j = 0 ; j <= min ( i , k ) ; j ++ ) { if ( j == 0 j == i ) C [ i ] [ j ] = 1 ; else C [ i ] [ j ] = C [ i - 1 ] [ j - 1 ] + C [ i - 1 ] [ j ] ; } } return C [ n ] [ k ] ; } int findMax ( int n ) { return binomialCoeff ( n , n / 2 ) ; } int main ( ) { int n = 5 ; cout << findMax ( n ) ; return 0 ; } |
Length of the smallest sub | C ++ program to find the length of the smallest substring consisting of maximum distinct characters ; Find maximum distinct characters in any string ; Initialize all character 's count with 0 ; Increase the count in array if a character is found ; size of given string ; Find maximum distinct characters in any string ; result ; Brute force approach to find all substrings ; We have to check here both conditions together 1. substring ' s β distinct β characters β is β equal β β to β maximum β distinct β characters β β 2 . β substring ' s length should be minimum ; Driver program to test above function ; Input String | #include <bits/stdc++.h> NEW_LINE using namespace std ; #define NO_OF_CHARS 256 NEW_LINE int max_distinct_char ( string str , int n ) { int count [ NO_OF_CHARS ] = { 0 } ; for ( int i = 0 ; i < n ; i ++ ) count [ str [ i ] ] ++ ; int max_distinct = 0 ; for ( int i = 0 ; i < NO_OF_CHARS ; i ++ ) if ( count [ i ] != 0 ) max_distinct ++ ; return max_distinct ; } int smallesteSubstr_maxDistictChar ( string str ) { int n = str . size ( ) ; int max_distinct = max_distinct_char ( str , n ) ; int minl = n ; for ( int i = 0 ; i < n ; i ++ ) { for ( int j = 0 ; j < n ; j ++ ) { string subs = str . substr ( i , j ) ; int subs_lenght = subs . size ( ) ; int sub_distinct_char = max_distinct_char ( subs , subs_lenght ) ; if ( subs_lenght < minl && max_distinct == sub_distinct_char ) { minl = subs_lenght ; } } } return minl ; } int main ( ) { string str = " AABBBCBB " ; int len = smallesteSubstr_maxDistictChar ( str ) ; cout << " β The β length β of β the β smallest β substring " " β consisting β of β maximum β distinct β " " characters β : β " << len ; return 0 ; } |
Find two co | C ++ implementation of the approach ; Function to find the required numbers ; GCD of the given numbers ; Printing the required numbers ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; void findNumbers ( int a , int b ) { int gcd = __gcd ( a , b ) ; cout << ( a / gcd ) << " β " << ( b / gcd ) ; } int main ( ) { int a = 12 , b = 16 ; findNumbers ( a , b ) ; return 0 ; } |
Find the remaining balance after the transaction | C ++ program to find the remaining balance ; Function to find the balance ; Check if the transaction can be successful or not ; Transaction is successful ; Transaction is unsuccessful ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; void findBalance ( int x , float bal ) { if ( x % 10 == 0 && ( ( float ) x + 1.50 ) <= bal ) { cout << fixed << setprecision ( 2 ) << ( bal - x - 1.50 ) << endl ; } else { cout << fixed << setprecision ( 2 ) << ( bal ) << endl ; } } int main ( ) { int x = 50 ; float bal = 100.50 ; findBalance ( x , bal ) ; return 0 ; } |
Count number of pairs in array having sum divisible by K | SET 2 | C ++ Program to count pairs whose sum divisible by ' K ' ; Program to count pairs whose sum divisible by ' K ' ; Create a frequency array to count occurrences of all remainders when divided by K ; To store count of pairs . ; Traverse the array , compute the remainder and add k - remainder value hash count to ans ; Count number of ( A [ i ] , ( K - rem ) % K ) pairs ; Increment count of remainder in hash map ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int countKdivPairs ( int A [ ] , int n , int K ) { int freq [ K ] = { 0 } ; int ans = 0 ; for ( int i = 0 ; i < n ; i ++ ) { int rem = A [ i ] % K ; ans += freq [ ( K - rem ) % K ] ; freq [ rem ] ++ ; } return ans ; } int main ( ) { int A [ ] = { 2 , 2 , 1 , 7 , 5 , 3 } ; int n = sizeof ( A ) / sizeof ( A [ 0 ] ) ; int K = 4 ; cout << countKdivPairs ( A , n , K ) ; return 0 ; } |
Minimum number of Bottles visible when a bottle can be enclosed inside another Bottle | C ++ code for the above approach ; Driver code ; Find the solution | #include <bits/stdc++.h> NEW_LINE using namespace std ; void min_visible_bottles ( int * arr , int n ) { map < int , int > m ; int ans = 0 ; for ( int i = 0 ; i < n ; i ++ ) { m [ arr [ i ] ] ++ ; ans = max ( ans , m [ arr [ i ] ] ) ; } cout << " Minimum β number β of β " << " Visible β Bottles β are : β " << ans << endl ; } int main ( ) { int n = 8 ; int arr [ ] = { 1 , 1 , 2 , 3 , 4 , 5 , 5 , 4 } ; min_visible_bottles ( arr , n ) ; return 0 ; } |
Number of even substrings in a string of digits | C ++ program to count number of substring which are even integer in a string of digits . ; Return the even number substrings . ; If current digit is even , add count of substrings ending with it . The count is ( i + 1 ) ; Driven Program | #include <bits/stdc++.h> NEW_LINE using namespace std ; int evenNumSubstring ( char str [ ] ) { int len = strlen ( str ) ; int count = 0 ; for ( int i = 0 ; i < len ; i ++ ) { int temp = str [ i ] - '0' ; if ( temp % 2 == 0 ) count += ( i + 1 ) ; } return count ; } int main ( ) { char str [ ] = "1234" ; cout << evenNumSubstring ( str ) << endl ; return 0 ; } |
Remove Nth node from end of the Linked List | CPP program to delete nth node from last ; Structure of node ; Function to insert node in a linked list ; Function to remove nth node from last ; To store length of the linked list ; B > length , then we can 't remove node ; We need to remove head node ; Return head -> next ; Remove len - B th node from starting ; This function prints contents of linked list starting from the given node ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; struct Node { int data ; struct Node * next ; } ; struct Node * create ( struct Node * head , int x ) { struct Node * temp , * ptr = head ; temp = new Node ( ) ; temp -> data = x ; temp -> next = NULL ; if ( head == NULL ) head = temp ; else { while ( ptr -> next != NULL ) { ptr = ptr -> next ; } ptr -> next = temp ; } return head ; } Node * removeNthFromEnd ( Node * head , int B ) { int len = 0 ; Node * tmp = head ; while ( tmp != NULL ) { len ++ ; tmp = tmp -> next ; } if ( B > len ) { cout << " Length β of β the β linked β list β is β " << len ; cout << " β we β can ' t β remove β " << B << " th β node β from β the " ; cout << " β linked β list STRNEWLINE " ; return head ; } else if ( B == len ) { return head -> next ; } else { int diff = len - B ; Node * prev = NULL ; Node * curr = head ; for ( int i = 0 ; i < diff ; i ++ ) { prev = curr ; curr = curr -> next ; } prev -> next = curr -> next ; return head ; } } void display ( struct Node * head ) { struct Node * temp = head ; while ( temp != NULL ) { cout << temp -> data << " β " ; temp = temp -> next ; } cout << endl ; } int main ( ) { struct Node * head = NULL ; head = create ( head , 1 ) ; head = create ( head , 2 ) ; head = create ( head , 3 ) ; head = create ( head , 4 ) ; head = create ( head , 5 ) ; int n = 2 ; cout << " Linked β list β before β modification : β STRNEWLINE " ; display ( head ) ; head = removeNthFromEnd ( head , 2 ) ; cout << " Linked β list β after β modification : β STRNEWLINE " ; display ( head ) ; return 0 ; } |
Find the final sequence of the array after performing given operations | C ++ implementation of the approach ; Function that generates the array b [ ] when n is even ; Fill the first half of the final array with reversed sequence ; Fill the second half ; Function that generates the array b [ ] when n is odd ; Fill the first half of the final array with reversed sequence ; Fill the second half ; Function to find the final array b [ ] after n operations of given type ; Create the array b ; If the array size is even ; Print the final array elements ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; void solveEven ( int n , int * arr , int * b ) { int left = n - 1 ; for ( int i = 0 ; i < ( n / 2 ) ; ++ i ) { b [ i ] = arr [ left ] ; left = left - 2 ; if ( left < 0 ) break ; } int right = 0 ; for ( int i = n / 2 ; i <= n - 1 ; ++ i ) { b [ i ] = arr [ right ] ; right = right + 2 ; if ( right > n - 2 ) break ; } } void solveOdd ( int n , int * arr , int * b ) { int left = n - 1 ; for ( int i = 0 ; i < ( n / 2 ) + 1 ; ++ i ) { b [ i ] = arr [ left ] ; left = left - 2 ; if ( left < 0 ) break ; } int right = 1 ; for ( int i = ( n / 2 ) + 1 ; i <= n - 1 ; ++ i ) { b [ i ] = arr [ right ] ; right = right + 2 ; if ( right > n - 2 ) break ; } } void solve ( int n , int * arr ) { int b [ n ] ; if ( n % 2 == 0 ) solveEven ( n , arr , b ) ; else solveOdd ( n , arr , b ) ; for ( int i = 0 ; i <= n - 1 ; ++ i ) { cout << b [ i ] << " β " ; } } int main ( ) { int arr [ ] = { 1 , 2 , 3 , 4 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; solve ( n , arr ) ; return 0 ; } |
Find the sum of the first half and second half elements of an array | C ++ program to find the sum of the first half elements and second half elements of an array ; Function to find the sum of the first half elements and second half elements of an array ; Add elements in first half sum ; Add elements in the second half sum ; Driver Code ; Function call | #include <bits/stdc++.h> NEW_LINE using namespace std ; void sum_of_elements ( int arr [ ] , int n ) { int sumfirst = 0 , sumsecond = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( i < n / 2 ) sumfirst += arr [ i ] ; else sumsecond += arr [ i ] ; } cout << " Sum β of β first β half β elements β is β " << sumfirst << endl ; cout << " Sum β of β second β half β elements β is β " << sumsecond << endl ; } int main ( ) { int arr [ ] = { 20 , 30 , 60 , 10 , 25 , 15 , 40 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; sum_of_elements ( arr , n ) ; return 0 ; } |
Sequence with sum K and minimum sum of absolute differences between consecutive elements | C ++ implementation of the approach ; Function to return the minimized sum ; If k is divisible by n then the answer will be 0 ; Else the answer will be 1 ; Driver code | #include <iostream> NEW_LINE using namespace std ; int minimum_sum ( int n , int k ) { if ( k % n == 0 ) return 0 ; return 1 ; } int main ( ) { int n = 3 , k = 56 ; cout << minimum_sum ( n , k ) ; return 0 ; } |
Print first N terms of Lower Wythoff sequence | C ++ implementation of the approach ; Function to print the first n terms of the lower Wythoff sequence ; Calculate value of phi ; Find the numbers ; a ( n ) = floor ( n * phi ) ; Print the nth numbers ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; void lowerWythoff ( int n ) { double phi = ( 1 + sqrt ( 5 ) ) / 2.0 ; for ( int i = 1 ; i <= n ; i ++ ) { double ans = floor ( i * phi ) ; cout << ans ; if ( i != n ) cout << " , β " ; } } int main ( ) { int n = 5 ; lowerWythoff ( n ) ; return 0 ; } |
Create new linked list from two given linked list with greater element at each node | C ++ program to create a new linked list from two given linked list of the same size with the greater element among the two at each node ; Representation of node ; Function to insert node in a linked list ; Function which returns new linked list ; Compare for greater node ; Driver code ; First linked list ; Second linked list | #include <iostream> NEW_LINE using namespace std ; struct Node { int data ; Node * next ; } ; void insert ( Node * * root , int item ) { Node * ptr , * temp ; temp = new Node ; temp -> data = item ; temp -> next = NULL ; if ( * root == NULL ) * root = temp ; else { ptr = * root ; while ( ptr -> next != NULL ) ptr = ptr -> next ; ptr -> next = temp ; } } Node * newList ( Node * root1 , Node * root2 ) { Node * ptr1 = root1 , * ptr2 = root2 , * ptr ; Node * root = NULL , * temp ; while ( ptr1 != NULL ) { temp = new Node ; temp -> next = NULL ; if ( ptr1 -> data < ptr2 -> data ) temp -> data = ptr2 -> data ; else temp -> data = ptr1 -> data ; if ( root == NULL ) root = temp ; else { ptr = root ; while ( ptr -> next != NULL ) ptr = ptr -> next ; ptr -> next = temp ; } ptr1 = ptr1 -> next ; ptr2 = ptr2 -> next ; } return root ; } void display ( Node * root ) { while ( root != NULL ) { cout << root -> data << " - > " ; root = root -> next ; } cout << endl ; } int main ( ) { Node * root1 = NULL , * root2 = NULL , * root = NULL ; insert ( & root1 , 5 ) ; insert ( & root1 , 2 ) ; insert ( & root1 , 3 ) ; insert ( & root1 , 8 ) ; cout << " First β List : β " ; display ( root1 ) ; insert ( & root2 , 1 ) ; insert ( & root2 , 7 ) ; insert ( & root2 , 4 ) ; insert ( & root2 , 5 ) ; cout << " Second β List : β " ; display ( root2 ) ; root = newList ( root1 , root2 ) ; cout << " New β List : TABSYMBOL " ; display ( root ) ; return 0 ; } |
Count of quadruplets from range [ L , R ] having GCD equal to K | C ++ implementation of the approach ; Function to return the count of quadruplets having gcd = k ; To store the required count ; Check every quadruplet pair whether its gcd is k ; Return the required count ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int countQuadruplets ( int l , int r , int k ) { int count = 0 ; for ( int u = l ; u <= r ; u ++ ) { for ( int v = l ; v <= r ; v ++ ) { for ( int w = l ; w <= r ; w ++ ) { for ( int x = l ; x <= r ; x ++ ) { if ( __gcd ( __gcd ( u , v ) , __gcd ( w , x ) ) == k ) count ++ ; } } } } return count ; } int main ( ) { int l = 1 , r = 10 , k = 2 ; cout << countQuadruplets ( l , r , k ) ; return 0 ; } |
Find an index such that difference between product of elements before and after it is minimum | C ++ implementation of the approach ; Function to return the index i such that the absolute difference between product of elements up to that index and the product of rest of the elements of the array is minimum ; To store the required index ; Prefix product array ; Compute the product array ; Iterate the product array to find the index ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; #define ll long long int NEW_LINE int findIndex ( int a [ ] , int n ) { int res ; ll min_diff = INT_MAX ; ll prod [ n ] ; prod [ 0 ] = a [ 0 ] ; for ( int i = 1 ; i < n ; i ++ ) prod [ i ] = prod [ i - 1 ] * a [ i ] ; for ( int i = 0 ; i < n - 1 ; i ++ ) { ll curr_diff = abs ( ( prod [ n - 1 ] / prod [ i ] ) - prod [ i ] ) ; if ( curr_diff < min_diff ) { min_diff = curr_diff ; res = i ; } } return res ; } int main ( ) { int arr [ ] = { 3 , 2 , 5 , 7 , 2 , 9 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << findIndex ( arr , N ) ; return 0 ; } |
Print all numbers whose set of prime factors is a subset of the set of the prime factors of X | C ++ program to implement the above approach ; Function to print all the numbers ; Iterate for every element in the array ; Find the gcd ; Iterate till gcd is 1 of number and x ; Divide the number by gcd ; Find the new gcdg ; If the number is 1 at the end then print the number ; If no numbers have been there ; Drivers code | #include <bits/stdc++.h> NEW_LINE using namespace std ; void printNumbers ( int a [ ] , int n , int x ) { bool flag = false ; for ( int i = 0 ; i < n ; i ++ ) { int num = a [ i ] ; int g = __gcd ( num , x ) ; while ( g != 1 ) { num /= g ; g = __gcd ( num , x ) ; } if ( num == 1 ) { flag = true ; cout << a [ i ] << " β " ; } } if ( ! flag ) cout << " There β are β no β such β numbers " ; } int main ( ) { int x = 60 ; int a [ ] = { 2 , 5 , 10 , 7 , 17 } ; int n = sizeof ( a ) / sizeof ( a [ 0 ] ) ; printNumbers ( a , n , x ) ; return 0 ; } |
Find the final radiations of each Radiated Stations | C ++ implementation of the approach ; Function to print the final radiations ; Function to create the array of the resultant radiations ; Resultant radiations ; Declaring index counter for left and right radiation ; Effective radiation for left and right case ; Radiation for i - th station ; Radiation increment for left stations ; Radiation increment for right stations ; Print the resultant radiation for each of the stations ; Driver code ; 1 - based indexing | #include <bits/stdc++.h> NEW_LINE using namespace std ; void print ( int rStation [ ] , int n ) { for ( int i = 1 ; i <= n ; i ++ ) cout << rStation [ i ] << " β " ; cout << endl ; } void radiated_Station ( int station [ ] , int n ) { int rStation [ n + 1 ] ; memset ( rStation , 0 , sizeof ( rStation ) ) ; for ( int i = 1 ; i <= n ; i ++ ) { int li = i - 1 , ri = i + 1 ; int lRad = station [ i ] - 1 , rRad = station [ i ] - 1 ; rStation [ i ] += station [ i ] ; while ( li >= 1 && lRad >= 1 ) { rStation [ li -- ] += lRad -- ; } while ( ri <= n && rRad >= 1 ) { rStation [ ri ++ ] += rRad -- ; } } print ( rStation , n ) ; } int main ( ) { int station [ ] = { 0 , 7 , 9 , 12 , 2 , 5 } ; int n = ( sizeof ( station ) / sizeof ( station [ 0 ] ) ) - 1 ; radiated_Station ( station , n ) ; return 0 ; } |
An in | C ++ implementation of above approach ; A utility function to reverse string str [ low . . high ] ; Cycle leader algorithm to move all even positioned elements at the end . ; odd index ; even index ; keep the back - up of element at new position ; The main function to transform a string . This function mainly uses cycleLeader ( ) to transform ; Step 1 : Find the largest prefix subarray of the form 3 ^ k + 1 ; Step 2 : Apply cycle leader algorithm for the largest subarrau ; Step 4.1 : Reverse the second half of first subarray ; Step 4.2 : Reverse the first half of second sub - string . ; Step 4.3 Reverse the second half of first sub - string and first half of second sub - string together ; Increase the length of first subarray ; Driver program to test above function | #include <bits/stdc++.h> NEW_LINE using namespace std ; void reverse ( char * str , int low , int high ) { while ( low < high ) { swap ( & str [ low ] , & str [ high ] ) ; ++ low ; -- high ; } } void cycleLeader ( char * str , int shift , int len ) { int j ; char item ; for ( int i = 1 ; i < len ; i *= 3 ) { j = i ; item = str [ j + shift ] ; do { if ( j & 1 ) j = len / 2 + j / 2 ; else j /= 2 ; swap ( & str [ j + shift ] , & item ) ; } while ( j != i ) ; } } void moveNumberToSecondHalf ( char * str ) { int k , lenFirst ; int lenRemaining = strlen ( str ) ; int shift = 0 ; while ( lenRemaining ) { k = 0 ; while ( pow ( 3 , k ) + 1 <= lenRemaining ) k ++ ; lenFirst = pow ( 3 , k - 1 ) + 1 ; lenRemaining -= lenFirst ; cycleLeader ( str , shift , lenFirst ) ; reverse ( str , shift / 2 , shift - 1 ) ; reverse ( str , shift , shift + lenFirst / 2 - 1 ) ; reverse ( str , shift / 2 , shift + lenFirst / 2 - 1 ) ; shift += lenFirst ; } } int main ( ) { char str [ ] = " a1b2c3d4e5f6g7" ; moveNumberToSecondHalf ( str ) ; cout << str ; return 0 ; } |
Program to find the maximum difference between the index of any two different numbers | C ++ implementation of the approach ; Function to return the maximum difference ; Iteratively check from back ; Different numbers ; Iteratively check from the beginning ; Different numbers ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int findMaximumDiff ( int a [ ] , int n ) { int ind1 = 0 ; for ( int i = n - 1 ; i > 0 ; i -- ) { if ( a [ 0 ] != a [ i ] ) { ind1 = i ; break ; } } int ind2 = 0 ; for ( int i = 0 ; i < n - 1 ; i ++ ) { if ( a [ n - 1 ] != a [ i ] ) { ind2 = ( n - 1 - i ) ; break ; } } return max ( ind1 , ind2 ) ; } int main ( ) { int a [ ] = { 1 , 2 , 3 , 2 , 3 } ; int n = sizeof ( a ) / sizeof ( a [ 0 ] ) ; cout << findMaximumDiff ( a , n ) ; return 0 ; } |
Find the Kth node in the DFS traversal of a given subtree in a Tree | C ++ program to find the Kth node in the DFS traversal of the subtree of given vertex V in a Tree ; To store nodes ; To store the current index of vertex in DFS ; To store the starting index and ending index of vertex in the DFS traversal array ; To store the DFS of vertex 1 ; Function to add edge between two nodes ; Initialize the vectors ; Function to perform DFS of a vertex 1. stores the DFS of the vertex 1 in vector p , 2. store the start index of DFS of every vertex 3. store the end index of DFS of every vertex ; store staring index of node ch ; store ending index ; Function to find the Kth node in DFS of vertex V ; check if kth number exits or not ; Driver code ; number of nodes ; add edges ; store DFS of 1 st node | #include <bits/stdc++.h> NEW_LINE using namespace std ; #define N 100005 NEW_LINE int n ; vector < int > tree [ N ] ; int currentIdx ; vector < int > startIdx , endIdx ; vector < int > p ; void Add_edge ( int u , int v ) { tree [ u ] . push_back ( v ) ; tree [ v ] . push_back ( u ) ; } void intisalise ( ) { startIdx . resize ( n ) ; endIdx . resize ( n ) ; p . resize ( n ) ; } void Dfs ( int ch , int par ) { p [ currentIdx ] = ch ; startIdx [ ch ] = currentIdx ++ ; for ( auto c : tree [ ch ] ) { if ( c != par ) Dfs ( c , ch ) ; } endIdx [ ch ] = currentIdx - 1 ; } int findNode ( int v , int k ) { k += startIdx [ v ] - 1 ; if ( k <= endIdx [ v ] ) return p [ k ] ; return -1 ; } int main ( ) { n = 9 ; Add_edge ( 1 , 2 ) ; Add_edge ( 1 , 3 ) ; Add_edge ( 1 , 4 ) ; Add_edge ( 3 , 5 ) ; Add_edge ( 3 , 7 ) ; Add_edge ( 5 , 6 ) ; Add_edge ( 5 , 8 ) ; Add_edge ( 7 , 9 ) ; intisalise ( ) ; Dfs ( 1 , 0 ) ; int v = 3 , k = 4 ; cout << findNode ( v , k ) ; return 0 ; } |
Sum of the series Kn + ( K ( n | Function to return sum ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int sum ( int k , int n ) { int sum = pow ( k , n + 1 ) - pow ( k - 1 , n + 1 ) ; return sum ; } int main ( ) { int n = 3 ; int K = 3 ; cout << sum ( K , n ) ; } |
Check whether factorial of N is divisible by sum of first N natural numbers | Function to check whether a number is prime or not . ; Count variable to store the number of factors of ' num ' ; Counting the number of factors ; If number is prime return true ; Function to check for divisibility ; if ' n ' equals 1 then divisibility is possible ; Else check whether ' n + 1' is prime or not ; If ' n + 1' is prime then ' n ! ' is not divisible by ' n * ( n + 1 ) / 2' ; else divisibility occurs ; Driver Code ; Test for n = 3 ; Test for n = 4 | #include <bits/stdc++.h> NEW_LINE using namespace std ; bool is_prime ( int num ) { int count = 0 ; for ( int i = 1 ; i * i <= ( num ) ; i ++ ) { if ( ( num ) % i == 0 ) { if ( i * i != ( num ) ) count += 2 ; else count ++ ; } } if ( count == 2 ) return true ; else return false ; } string is_divisible ( int n ) { if ( n == 1 ) { return " YES " ; } else { if ( is_prime ( n + 1 ) ) return " NO " ; else return " YES " ; } } int main ( ) { int n ; n = 3 ; cout << is_divisible ( n ) << endl ; n = 4 ; cout << is_divisible ( n ) << endl ; return 0 ; } |
Number of subarrays having sum of the form k ^ m , m >= 0 | C ++ implementation of the above approach ; Function to count number of sub - arrays whose sum is k ^ p where p >= 0 ; If m [ a + b ] = c , then add c to the current sum . ; Increase count of prefix sum . ; If m [ a + b ] = c , then add c to the current sum . ; Increase count of prefix sum . ; b = k ^ p , p >= 0 ; k ^ m can be maximum equal to 10 ^ 14. ; If m [ a + b ] = c , then add c to the current sum . ; Increase count of prefix sum . ; Driver code | #include <bits/stdc++.h> NEW_LINE #define ll long long NEW_LINE #define MAX 100005 NEW_LINE using namespace std ; ll countSubarrays ( int * arr , int n , int k ) { ll prefix_sum [ MAX ] ; prefix_sum [ 0 ] = 0 ; partial_sum ( arr , arr + n , prefix_sum + 1 ) ; ll sum ; if ( k == 1 ) { sum = 0 ; map < ll , int > m ; for ( int i = n ; i >= 0 ; i -- ) { if ( m . find ( prefix_sum [ i ] + 1 ) != m . end ( ) ) sum += m [ prefix_sum [ i ] + 1 ] ; m [ prefix_sum [ i ] ] ++ ; } return sum ; } if ( k == -1 ) { sum = 0 ; map < ll , int > m ; for ( int i = n ; i >= 0 ; i -- ) { if ( m . find ( prefix_sum [ i ] + 1 ) != m . end ( ) ) sum += m [ prefix_sum [ i ] + 1 ] ; if ( m . find ( prefix_sum [ i ] - 1 ) != m . end ( ) ) sum += m [ prefix_sum [ i ] - 1 ] ; m [ prefix_sum [ i ] ] ++ ; } return sum ; } sum = 0 ; ll b ; map < ll , int > m ; for ( int i = n ; i >= 0 ; i -- ) { b = 1 ; while ( true ) { if ( b > 100000000000000 ) break ; if ( m . find ( prefix_sum [ i ] + b ) != m . end ( ) ) sum += m [ prefix_sum [ i ] + b ] ; b *= k ; } m [ prefix_sum [ i ] ] ++ ; } return sum ; } int main ( ) { int arr [ ] = { 2 , 2 , 2 , 2 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; int k = 2 ; cout << countSubarrays ( arr , n , k ) ; return 0 ; } |
Given two binary strings perform operation until B > 0 and print the result | C ++ implementation of the approach ; Function to return the required result ; Reverse the strings ; Count the number of set bits in b ; To store the powers of 2 ; power [ i ] = pow ( 2 , i ) % mod ; To store the final answer ; Add power [ i ] to the ans after multiplying it with the number of set bits in b ; Divide by 2 means right shift b >> 1 if b has 1 at right most side than number of set bits will get decreased ; If no more set bits in b i . e . b = 0 ; Return the required answer ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; #define ll long long NEW_LINE #define mod (int)(1e9 + 7) NEW_LINE ll BitOperations ( string a , int n , string b , int m ) { reverse ( a . begin ( ) , a . end ( ) ) ; reverse ( b . begin ( ) , b . end ( ) ) ; int c = 0 ; for ( int i = 0 ; i < m ; i ++ ) if ( b [ i ] == '1' ) c ++ ; ll power [ n ] ; power [ 0 ] = 1 ; for ( int i = 1 ; i < n ; i ++ ) power [ i ] = ( power [ i - 1 ] * 2 ) % mod ; ll ans = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( a [ i ] == '1' ) { ans += c * power [ i ] ; if ( ans >= mod ) ans %= mod ; } if ( b [ i ] == '1' ) c -- ; if ( c == 0 ) break ; } return ans ; } int main ( ) { string a = "1001" , b = "10101" ; int n = a . length ( ) , m = b . length ( ) ; cout << BitOperations ( a , n , b , m ) ; return 0 ; } |
Sum of sides of largest and smallest child polygons possible from a given polygon | Function to find the sum of largest and smallest secondary polygons if possible ; Count edges of primary polygon ; Calculate edges present in the largest secondary polygon ; Driver Code ; Given Exterior Angle | #include <bits/stdc++.h> NEW_LINE using namespace std ; void secondary_polygon ( int Angle ) { int edges_primary = 360 / Angle ; if ( edges_primary >= 6 ) { int edges_max_secondary = edges_primary / 2 ; cout << edges_max_secondary + 3 ; } else cout << " Not β Possible " ; } int main ( ) { int Angle = 45 ; secondary_polygon ( Angle ) ; return 0 ; } |
Print prime numbers with prime sum of digits in an array | C ++ implementation of the above approach ; Function to store the primes ; Function to return the sum of digits ; Function to print additive primes ; If the number is prime ; Check if it 's digit sum is prime ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; void sieve ( int maxEle , int prime [ ] ) { prime [ 0 ] = prime [ 1 ] = 1 ; for ( int i = 2 ; i * i <= maxEle ; i ++ ) { if ( ! prime [ i ] ) { for ( int j = 2 * i ; j <= maxEle ; j += i ) prime [ j ] = 1 ; } } } int digitSum ( int n ) { int sum = 0 ; while ( n ) { sum += n % 10 ; n = n / 10 ; } return sum ; } void printAdditivePrime ( int arr [ ] , int n ) { int maxEle = * max_element ( arr , arr + n ) ; int prime [ maxEle + 1 ] ; memset ( prime , 0 , sizeof ( prime ) ) ; sieve ( maxEle , prime ) ; for ( int i = 0 ; i < n ; i ++ ) { if ( prime [ arr [ i ] ] == 0 ) { int sum = digitSum ( arr [ i ] ) ; if ( prime [ sum ] == 0 ) cout << arr [ i ] << " β " ; } } } int main ( ) { int a [ ] = { 2 , 4 , 6 , 11 , 12 , 18 , 7 } ; int n = sizeof ( a ) / sizeof ( a [ 0 ] ) ; printAdditivePrime ( a , n ) ; return 0 ; } |
Program to find nth term of the series 1 4 15 24 45 60 92 | C ++ implementation of the above approach ; function to calculate nth term of the series ; variable nth will store the nth term of series ; if n is even ; if n is odd ; return nth term ; Driver code | #include <stdio.h> NEW_LINE long long int nthTerm ( long long int n ) { long long int nth ; if ( n % 2 == 0 ) nth = 2 * ( ( n * n ) - n ) ; else nth = ( 2 * n * n ) - n ; return nth ; } int main ( ) { long long int n ; n = 5 ; printf ( " % lld STRNEWLINE " , nthTerm ( n ) ) ; n = 25 ; printf ( " % lld STRNEWLINE " , nthTerm ( n ) ) ; n = 25000000 ; printf ( " % lld STRNEWLINE " , nthTerm ( n ) ) ; n = 250000007 ; printf ( " % lld STRNEWLINE " , nthTerm ( n ) ) ; return 0 ; } |
Find the Nth term of the series 9 , 45 , 243 , 1377 | C ++ implementation of the approach ; Function to return the nth term of the given series ; nth term ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; long nthterm ( int n ) { int An = ( pow ( 1 , n ) + pow ( 2 , n ) ) * pow ( 3 , n ) ; return An ; } int main ( ) { int n = 3 ; cout << nthterm ( n ) ; return 0 ; } |
Count the numbers < N which have equal number of divisors as K | C ++ implementation of the approach ; Function to return the count of the divisors of a number ; Count the number of 2 s that divide n ; n must be odd at this point . So we can skip one element ; While i divides n ; This condition is to handle the case when n is a prime number > 2 ; Count the total elements that have divisors exactly equal to as that of k 's ; Exclude k from the result if it is smaller than n . ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int countDivisors ( int n ) { int x = 0 , ans = 1 ; while ( n % 2 == 0 ) { x ++ ; n = n / 2 ; } ans = ans * ( x + 1 ) ; for ( int i = 3 ; i <= sqrt ( n ) ; i = i + 2 ) { x = 0 ; while ( n % i == 0 ) { x ++ ; n = n / i ; } ans = ans * ( x + 1 ) ; } if ( n > 2 ) ans = ans * 2 ; return ans ; } int getTotalCount ( int n , int k ) { int k_count = countDivisors ( k ) ; int count = 0 ; for ( int i = 1 ; i < n ; i ++ ) if ( k_count == countDivisors ( i ) ) count ++ ; if ( k < n ) count = count - 1 ; return count ; } int main ( ) { int n = 500 , k = 6 ; cout << getTotalCount ( n , k ) ; return 0 ; } |
Find the nth term of the series 0 , 8 , 64 , 216 , 512 , . . . | C ++ implementation of the approach ; Function to return the nth term of the given series ; Common difference ; First term ; nth term ; nth term of the given series ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; long term ( int n ) { int d = 2 ; int a1 = 0 ; int An = a1 + ( n - 1 ) * d ; An = pow ( An , 3 ) ; return An ; } int main ( ) { int n = 5 ; cout << term ( n ) ; return 0 ; } |
Find the type of triangle from the given sides | C ++ implementation to find the type of triangle with the help of the sides ; Function to find the type of triangle with the help of sides ; Driver Code ; Function Call | #include <bits/stdc++.h> NEW_LINE using namespace std ; void checkTypeOfTriangle ( int a , int b , int c ) { int sqa = pow ( a , 2 ) ; int sqb = pow ( b , 2 ) ; int sqc = pow ( c , 2 ) ; if ( sqa == sqb + sqc sqb == sqc + sqa sqc == sqa + sqb ) { cout << " Right - angled β Triangle " ; } else if ( sqa > sqc + sqb sqb > sqa + sqc sqc > sqa + sqb ) { cout << " Obtuse - angled β Triangle " ; } else { cout << " Acute - angled β Triangle " ; } } int main ( ) { int a , b , c ; a = 2 ; b = 2 ; c = 2 ; checkTypeOfTriangle ( a , b , c ) ; return 0 ; } |
Count the number of intervals in which a given value lies | C ++ program to count the number of intervals in which a given value lies ; Function to count the number of intervals in which a given value lies ; Variables to store overall minimum and maximum of the intervals ; Variables to store start and end of an interval ; Frequency array to keep track of how many of the given intervals an element lies in ; Constructing the frequency array ; Driver code ; length of the array | #include <bits/stdc++.h> NEW_LINE using namespace std ; const int MAX_VAL = 200000 ; int countIntervals ( int arr [ ] [ 2 ] , int V , int N ) { int min = INT_MAX ; int max = INT_MIN ; int li , ri ; int freq [ MAX_VAL ] ; for ( int i = 0 ; i < N ; i ++ ) { li = arr [ i ] [ 0 ] ; freq [ li ] = freq [ li ] + 1 ; ri = arr [ i ] [ 1 ] ; freq [ ri + 1 ] = freq [ ri + 1 ] - 1 ; if ( li < min ) min = li ; if ( ri > max ) max = ri ; } for ( int i = min ; i <= max ; i ++ ) freq [ i ] = freq [ i ] + freq [ i - 1 ] ; return freq [ V ] ; } int main ( ) { int arr [ 5 ] [ 2 ] = { { 1 , 10 } , { 5 , 10 } , { 15 , 25 } , { 7 , 12 } , { 20 , 25 } } ; int V = 7 ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << ( countIntervals ( arr , V , N ) ) ; } |
Check whether the triangle is valid or not if angles are given | C ++ implementation of the approach ; Function to check if sum of the three angles is 180 or not ; Check condition ; Driver code ; function calling and print output | #include <bits/stdc++.h> NEW_LINE using namespace std ; bool Valid ( int a , int b , int c ) { if ( a + b + c == 180 && a != 0 && b != 0 && c != 0 ) return true ; else return false ; } int main ( ) { int a = 60 , b = 40 , c = 80 ; if ( Valid ( a , b , c ) ) cout << " Valid " ; else cout << " Invalid " ; } |
Split N ^ 2 numbers into N groups of equal sum | C ++ implementation of the above approach ; Function to print N groups of equal sum ; No . of Groups ; n / 2 pairs ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; void printGroups ( int n ) { int x = 1 ; int y = n * n ; for ( int i = 1 ; i <= n ; i ++ ) { for ( int j = 1 ; j <= n / 2 ; j ++ ) { cout << " { β " << x << " , β " << y << " } β " ; x ++ ; y -- ; } cout << endl ; } } int main ( ) { int n = 4 ; printGroups ( n ) ; return 0 ; } |
Program to find the Break Even Point | C ++ program to find the break - even point . ; Function to calculate Break Even Point ; Calculating number of articles to be sold ; Main Function | #include <iostream> NEW_LINE #include <math.h> NEW_LINE using namespace std ; int breakEvenPoint ( int exp , int S , int M ) { float earn = S - M ; int res = ceil ( exp / earn ) ; return res ; } int main ( ) { int exp = 3550 , S = 90 , M = 65 ; cout << breakEvenPoint ( exp , S , M ) ; return 0 ; } |
Minimize the value of N by applying the given operations | C ++ implementation of the above approach ; function to return the product of distinct prime factors of a number ; find distinct prime ; Driver code | #include <bits/stdc++.h> NEW_LINE #define ll long long int NEW_LINE using namespace std ; ll minimum ( ll n ) { ll product = 1 ; for ( int i = 2 ; i * i <= n ; i ++ ) { if ( n % i == 0 ) { while ( n % i == 0 ) n = n / i ; product = product * i ; } } if ( n >= 2 ) product = product * n ; return product ; } int main ( ) { ll n = 20 ; cout << minimum ( n ) << endl ; return 0 ; } |
N digit numbers divisible by 5 formed from the M digits | CPP program to find the count of all possible N digit numbers which are divisible by 5 formed from M digits ; Function to find the count of all possible N digit numbers which are divisible by 5 formed from M digits ; If it is not possible to form n digit number from the given m digits without repetition ; If both zero and five exists ; Remaining N - 1 iterations ; Remaining N - 1 iterations ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int numbers ( int n , int arr [ ] , int m ) { int isZero = 0 , isFive = 0 ; int result = 0 ; if ( m < n ) { return -1 ; } for ( int i = 0 ; i < m ; i ++ ) { if ( arr [ i ] == 0 ) isZero = 1 ; if ( arr [ i ] == 5 ) isFive = 1 ; } if ( isZero && isFive ) { result = 2 ; for ( int i = 0 ; i < n - 1 ; i ++ ) { result = result * ( -- m ) ; } } else if ( isZero isFive ) { result = 1 ; for ( int i = 0 ; i < n - 1 ; i ++ ) { result = result * ( -- m ) ; } } else result = -1 ; return result ; } int main ( ) { int n = 3 , m = 6 ; int arr [ ] = { 2 , 3 , 5 , 6 , 7 , 9 } ; cout << numbers ( n , arr , m ) ; return 0 ; } |
Program to find the smallest element among three elements | C ++ implementation to find the smallest of three elements | #include <bits/stdc++.h> NEW_LINE using namespace std ; int main ( ) { int a = 5 , b = 7 , c = 10 ; if ( a <= b && a <= c ) cout << a << " β is β the β smallest " ; else if ( b <= a && b <= c ) cout << b << " β is β the β smallest " ; else cout << c << " β is β the β smallest " ; return 0 ; } |
Find subsequences with maximum Bitwise AND and Bitwise OR | C ++ implementation of above approach ; function to find the maximum sum ; Maximum And is maximum element ; Maximum OR is bitwise OR of all ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; void maxSum ( int a [ ] , int n ) { int maxAnd = 0 ; for ( int i = 0 ; i < n ; i ++ ) maxAnd = max ( maxAnd , a [ i ] ) ; int maxOR = 0 ; for ( int i = 0 ; i < n ; i ++ ) { maxOR = maxOR | a [ i ] ; } cout << maxAnd + maxOR ; } int main ( ) { int a [ ] = { 3 , 5 , 6 , 1 } ; int n = sizeof ( a ) / sizeof ( a [ 0 ] ) ; maxSum ( a , n ) ; } |
Count Magic squares in a grid | CPP program to count magic squares ; function to check is subgrid is Magic Square ; Elements of grid must contain all numbers from 1 to 9 , sum of all rows , columns and diagonals must be same , i . e . , 15. ; Function to count total Magic square subgrids ; if condition true skip check ; check for magic square subgrid ; return total magic square ; Driver program ; function call to print required answer | #include <bits/stdc++.h> NEW_LINE using namespace std ; const int R = 3 ; const int C = 4 ; int magic ( int a , int b , int c , int d , int e , int f , int g , int h , int i ) { set < int > s1 = { a , b , c , d , e , f , g , h , i } , s2 = { 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 } ; if ( s1 == s2 && ( a + b + c ) == 15 && ( d + e + f ) == 15 && ( g + h + i ) == 15 && ( a + d + g ) == 15 && ( b + e + h ) == 15 && ( c + f + i ) == 15 && ( a + e + i ) == 15 && ( c + e + g ) == 15 ) return true ; return false ; } int CountMagicSquare ( int Grid [ R ] [ C ] ) { int ans = 0 ; for ( int i = 0 ; i < R - 2 ; i ++ ) for ( int j = 0 ; j < C - 2 ; j ++ ) { if ( Grid [ i + 1 ] [ j + 1 ] != 5 ) continue ; if ( magic ( Grid [ i ] [ j ] , Grid [ i ] [ j + 1 ] , Grid [ i ] [ j + 2 ] , Grid [ i + 1 ] [ j ] , Grid [ i + 1 ] [ j + 1 ] , Grid [ i + 1 ] [ j + 2 ] , Grid [ i + 2 ] [ j ] , Grid [ i + 2 ] [ j + 1 ] , Grid [ i + 2 ] [ j + 2 ] ) ) ans += 1 ; } return ans ; } int main ( ) { int G [ R ] [ C ] = { { 4 , 3 , 8 , 4 } , { 9 , 5 , 1 , 9 } , { 2 , 7 , 6 , 2 } } ; cout << CountMagicSquare ( G ) ; return 0 ; } |
Sum of minimum elements of all subarrays | CPP implementation of above approach ; Function to return required minimum sum ; getting number of element strictly larger than A [ i ] on Left . ; get elements from stack until element greater than A [ i ] found ; getting number of element larger than A [ i ] on Right . ; get elements from stack until element greater or equal to A [ i ] found ; calculating required resultult ; Driver program ; function call to get required resultult | #include <bits/stdc++.h> NEW_LINE using namespace std ; int sumSubarrayMins ( int A [ ] , int n ) { int left [ n ] , right [ n ] ; stack < pair < int , int > > s1 , s2 ; for ( int i = 0 ; i < n ; ++ i ) { int cnt = 1 ; while ( ! s1 . empty ( ) && ( s1 . top ( ) . first ) > A [ i ] ) { cnt += s1 . top ( ) . second ; s1 . pop ( ) ; } s1 . push ( { A [ i ] , cnt } ) ; left [ i ] = cnt ; } for ( int i = n - 1 ; i >= 0 ; -- i ) { int cnt = 1 ; while ( ! s2 . empty ( ) && ( s2 . top ( ) . first ) >= A [ i ] ) { cnt += s2 . top ( ) . second ; s2 . pop ( ) ; } s2 . push ( { A [ i ] , cnt } ) ; right [ i ] = cnt ; } int result = 0 ; for ( int i = 0 ; i < n ; ++ i ) result = ( result + A [ i ] * left [ i ] * right [ i ] ) ; return result ; } int main ( ) { int A [ ] = { 3 , 1 , 2 , 4 } ; int n = sizeof ( A ) / sizeof ( A [ 0 ] ) ; cout << sumSubarrayMins ( A , n ) ; return 0 ; } |
Minimum and Maximum element of an array which is divisible by a given number k | C ++ implementation of the above approach ; Function to find the minimum element ; Function to find the maximum element ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int getMin ( int arr [ ] , int n , int k ) { int res = INT_MAX ; for ( int i = 0 ; i < n ; i ++ ) { if ( arr [ i ] % k == 0 ) res = min ( res , arr [ i ] ) ; } return res ; } int getMax ( int arr [ ] , int n , int k ) { int res = INT_MIN ; for ( int i = 1 ; i < n ; i ++ ) { if ( arr [ i ] % k == 0 ) res = max ( res , arr [ i ] ) ; } return res ; } int main ( ) { int arr [ ] = { 10 , 1230 , 45 , 67 , 1 } ; int k = 10 ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << " Minimum β element β of β array β which β is β divisible β by β k : β " << getMin ( arr , n , k ) << " STRNEWLINE " ; cout << " Maximum β element β of β array β which β is β divisible β by β k : β " << getMax ( arr , n , k ) ; return 0 ; } |
Print a number containing K digits with digital root D | C ++ implementation of the above approach ; Function to find a number ; If d is 0 k has to be 1 ; Print k - 1 zeroes ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; void printNumberWithDR ( int k , int d ) { if ( d == 0 && k != 1 ) cout << " - 1" ; else { cout << d ; k -- ; while ( k -- ) cout << "0" ; } } int main ( ) { int k = 4 , d = 4 ; printNumberWithDR ( k , d ) ; return 0 ; } |
Count number of integers less than or equal to N which has exactly 9 divisors | C ++ implementation of above approach ; Function to count numbers having exactly 9 divisors ; Sieve array ; initially prime [ i ] = i ; use sieve concept to store the first prime factor of every number ; mark all factors of i ; check for all numbers if they can be expressed in form p * q ; p prime factor ; q prime factor ; if both prime factors are different if p * q <= n and q != ; Check if it can be expressed as p ^ 8 ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int countNumbers ( int n ) { int c = 0 ; int limit = sqrt ( n ) ; int prime [ limit + 1 ] ; for ( int i = 1 ; i <= limit ; i ++ ) prime [ i ] = i ; for ( int i = 2 ; i * i <= limit ; i ++ ) { if ( prime [ i ] == i ) { for ( int j = i * i ; j <= limit ; j += i ) if ( prime [ j ] == j ) prime [ j ] = i ; } } for ( int i = 2 ; i <= limit ; i ++ ) { int p = prime [ i ] ; int q = prime [ i / prime [ i ] ] ; if ( p * q == i && q != 1 && p != q ) { c += 1 ; } else if ( prime [ i ] == i ) { if ( pow ( i , 8 ) <= n ) { c += 1 ; } } } return c ; } int main ( ) { int n = 1000 ; cout << countNumbers ( n ) ; return 0 ; } |
Interprime | CPP program to check if a number is interprime or not ; Function to check if a number is prime or not ; Corner cases ; This is checked so that we can skip middle five numbers in below loop ; Function to check if the given number is interprime or not ; Smallest Interprime is 4 So the number less than 4 can not be a Interprime ; Calculate first prime number < n ; Calculate first prime number > n ; Check if prev_prime and next_prime have the same average ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; bool isPrime ( int n ) { if ( n <= 1 ) return false ; if ( n <= 3 ) return true ; if ( n % 2 == 0 n % 3 == 0 ) return false ; for ( int i = 5 ; i * i <= n ; i = i + 6 ) { if ( n % i == 0 || n % ( i + 2 ) == 0 ) { return false ; } } return true ; } bool isInterprime ( int n ) { if ( n < 4 ) return false ; int prev_prime = n ; int next_prime = n ; while ( ! isPrime ( prev_prime ) ) { prev_prime -- ; } while ( ! isPrime ( next_prime ) ) { next_prime ++ ; } if ( ( prev_prime + next_prime ) == 2 * n ) return true ; else return false ; } int main ( ) { int n = 9 ; if ( isInterprime ( n ) ) cout << " YES " ; else cout << " NO " ; return 0 ; } |
Find the unit place digit of sum of N factorials | C ++ program to find the unit place digit of the first N natural numbers factorials ; Function to find the unit 's place digit ; Let us write for cases when N is smaller than or equal to 4. ; We know following ( 1 ! + 2 ! + 3 ! + 4 ! ) % 10 = 3 else ( N >= 4 ) ; Driver code | #include <iostream> NEW_LINE using namespace std ; int get_unit_digit ( long long int N ) { if ( N == 0 N == 1 ) return 1 ; else if ( N == 2 ) return 3 ; else if ( N == 3 ) return 9 ; return 3 ; } int main ( ) { long long int N = 1 ; for ( N = 0 ; N <= 10 ; N ++ ) cout << " For β N β = β " << N << " β : β " << get_unit_digit ( N ) << endl ; return 0 ; } |
Sum of squares of Fibonacci numbers | C ++ Program to find sum of squares of Fibonacci numbers in O ( Log n ) time . ; Create an array for memoization ; Returns n 'th Fibonacci number using table f[] ; Base cases ; If fib ( n ) is already computed ; Applying above formula [ Note value n & 1 is 1 if n is odd , else 0 ] . ; Function to calculate sum of squares of Fibonacci numbers ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; const int MAX = 1000 ; int f [ MAX ] = { 0 } ; int fib ( int n ) { if ( n == 0 ) return 0 ; if ( n == 1 n == 2 ) return ( f [ n ] = 1 ) ; if ( f [ n ] ) return f [ n ] ; int k = ( n & 1 ) ? ( n + 1 ) / 2 : n / 2 ; f [ n ] = ( n & 1 ) ? ( fib ( k ) * fib ( k ) + fib ( k - 1 ) * fib ( k - 1 ) ) : ( 2 * fib ( k - 1 ) + fib ( k ) ) * fib ( k ) ; return f [ n ] ; } int calculateSumOfSquares ( int n ) { return fib ( n ) * fib ( n + 1 ) ; } int main ( ) { int n = 6 ; cout << " Sum β of β Squares β of β Fibonacci β numbers β is β : β " << calculateSumOfSquares ( n ) << endl ; return 0 ; } |
Number of solutions for the equation x + y + z <= n | CPP program to find the number of solutions for the equation x + y + z <= n , such that 0 <= x <= X , 0 <= y <= Y , 0 <= z <= Z . ; function to find the number of solutions for the equation x + y + z <= n , such that 0 <= x <= X , 0 <= y <= Y , 0 <= z <= Z . ; to store answer ; for values of x ; for values of y ; maximum possible value of z ; if z value greater than equals to 0 then only it is valid ; find minimum of temp and z ; return required answer ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int NumberOfSolutions ( int x , int y , int z , int n ) { int ans = 0 ; for ( int i = 0 ; i <= x ; i ++ ) { for ( int j = 0 ; j <= y ; j ++ ) { int temp = n - i - j ; if ( temp >= 0 ) { temp = min ( temp , z ) ; ans += temp + 1 ; } } } return ans ; } int main ( ) { int x = 1 , y = 2 , z = 3 , n = 4 ; cout << NumberOfSolutions ( x , y , z , n ) ; return 0 ; } |
Program to find the Nth term of series 5 , 12 , 21 , 32 , 45. ... . . | CPP program to find the N - th term of the series : 5 , 12 , 21 , 32 , 45. . ... . ; calculate Nth term of series ; Driver code | #include <iostream> NEW_LINE #include <math.h> NEW_LINE using namespace std ; int nthTerm ( int n ) { return pow ( n , 2 ) + 4 * n ; } int main ( ) { int N = 4 ; cout << nthTerm ( N ) << endl ; return 0 ; } |
Numbers less than N which are product of exactly two distinct prime numbers | C ++ program to find numbers that are product of exactly two distinct prime numbers ; Function to check whether a number is a PerfectSquare or not ; Function to check if a number is a product of exactly two distinct primes ; Function to find numbers that are product of exactly two distinct prime numbers . ; Vector to store such numbers ; insert in the vector ; Print all numbers till n from the vector ; Driver function | #include <bits/stdc++.h> NEW_LINE using namespace std ; bool isPerfectSquare ( long double x ) { long double sr = sqrt ( x ) ; return ( ( sr - floor ( sr ) ) == 0 ) ; } bool isProduct ( int num ) { int cnt = 0 ; for ( int i = 2 ; cnt < 2 && i * i <= num ; ++ i ) { while ( num % i == 0 ) { num /= i ; ++ cnt ; } } if ( num > 1 ) ++ cnt ; return cnt == 2 ; } void findNumbers ( int N ) { vector < int > vec ; for ( int i = 1 ; i <= N ; i ++ ) { if ( isProduct ( i ) && ! isPerfectSquare ( i ) ) { vec . push_back ( i ) ; } } for ( int i = 0 ; i < vec . size ( ) ; i ++ ) { cout << vec [ i ] << " β " ; } } int main ( ) { int N = 30 ; findNumbers ( N ) ; return 0 ; } |
Program to find the Nth term of the series 3 , 20 , 63 , 144 , 230 , Γ’ β¬Β¦ Γ’ β¬Β¦ | CPP program to find N - th term of the series : 3 , 20 , 63 , 144 , 230 . ... . ; calculate Nth term of series ; return final sum ; Driver code | #include <iostream> NEW_LINE #include <math.h> NEW_LINE using namespace std ; int nthTerm ( int n ) { return 2 * pow ( n , 3 ) + pow ( n , 2 ) ; } int main ( ) { int N = 3 ; cout << nthTerm ( N ) ; return 0 ; } |
Find Nth number of the series 1 , 6 , 15 , 28 , 45 , ... . . | CPP program to find Nth term of the series ; function to return nth term of the series ; Driver code ; Taking n as 4 ; Printing the nth term | #include <bits/stdc++.h> NEW_LINE using namespace std ; #define mod 1000000009 NEW_LINE int NthTerm ( long long n ) { long long x = ( 2 * n * n ) % mod ; return ( x - n + mod ) % mod ; } int main ( ) { long long N = 4 ; cout << NthTerm ( N ) ; return 0 ; } |
Program to print the Sum of series | CPP program to find SUM upto N - th term of the series : - 1 , 2 , 11 , 26 , 47 , 74 , ... . . ; calculate Nth term of series ; Driver Function ; Get the value of N ; Get the sum of the series | #include <iostream> NEW_LINE using namespace std ; int findSum ( int N ) { return ( N * ( N + 1 ) * ( 2 * N - 5 ) + 4 * N ) / 2 ; } int main ( ) { int N = 3 ; cout << findSum ( N ) << endl ; return 0 ; } |
Program to find the Nth term of series | CPP program to find N - th term of the series : 9 , 23 , 45 , 75 , 113 , 159. . ... . ; calculate Nth term of series ; Driver Function ; Get the value of N ; Find the Nth term and print it | #include <iostream> ; using namespace std ; int nthTerm ( int N ) { return ( ( 3 * N * N ) - ( 6 * N ) + 2 ) ; } int main ( ) { int N = 3 ; cout << nthTerm ( N ) ; return 0 ; } |
Program to find the value of tan ( nΓ Λ ) | C ++ program to find the value of cos ( n - theta ) ; This function use to calculate the binomial coefficient upto 15 ; use simple DP to find coefficient ; Function to find the value of ; store required answer ; use to toggle sign in sequence . ; calculate numerator ; calculate denominator ; Driver code . | #include <bits/stdc++.h> NEW_LINE #define ll long long int NEW_LINE #define MAX 16 NEW_LINE using namespace std ; ll nCr [ MAX ] [ MAX ] = { 0 } ; void binomial ( ) { for ( int i = 0 ; i < MAX ; i ++ ) { for ( int j = 0 ; j <= i ; j ++ ) { if ( j == 0 j == i ) nCr [ i ] [ j ] = 1 ; else nCr [ i ] [ j ] = nCr [ i - 1 ] [ j ] + nCr [ i - 1 ] [ j - 1 ] ; } } } double findTanNTheta ( double tanTheta , ll n ) { double ans = 0 , numerator = 0 , denominator = 0 ; ll toggle = 1 ; for ( int i = 1 ; i <= n ; i += 2 ) { numerator = numerator + nCr [ n ] [ i ] * pow ( tanTheta , i ) * toggle ; toggle = toggle * -1 ; } denominator = 1 ; toggle = -1 ; for ( int i = 2 ; i <= n ; i += 2 ) { numerator = numerator + nCr [ n ] [ i ] * pow ( tanTheta , i ) * toggle ; toggle = toggle * -1 ; } ans = numerator / denominator ; return ans ; } int main ( ) { binomial ( ) ; double tanTheta = 0.3 ; ll n = 10 ; cout << findTanNTheta ( tanTheta , n ) << endl ; return 0 ; } |
Pizza cut problem ( Or Circle Division by Lines ) | C ++ program to find maximum no of pieces by given number of cuts ; Function for finding maximum pieces with n cuts . ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int findMaximumPieces ( int n ) { return 1 + n * ( n + 1 ) / 2 ; } int main ( ) { cout << findMaximumPieces ( 3 ) ; return 0 ; } |
Optimum location of point to minimize total distance | C / C ++ program to find optimum location and total cost ; structure defining a point ; structure defining a line of ax + by + c = 0 form ; method to get distance of point ( x , y ) from point p ; Utility method to compute total distance all points when choose point on given line has x - coordinate value as X ; calculating Y of chosen point by line equation ; Utility method to find minimum total distance ; loop until difference between low and high become less than EPS ; mid1 and mid2 are representative x co - ordiantes of search space ; if mid2 point gives more total distance , skip third part ; if mid1 point gives more total distance , skip first part ; compute optimum distance cost by sending average of low and high as X ; method to find optimum cost ; converting 2D array input to point array ; Driver code to test above method | #include <bits/stdc++.h> NEW_LINE using namespace std ; #define sq ( x ) ((x) * (x)) NEW_LINE #define EPS 1e-6 NEW_LINE #define N 5 NEW_LINE struct point { int x , y ; point ( ) { } point ( int x , int y ) : x ( x ) , y ( y ) { } } ; struct line { int a , b , c ; line ( int a , int b , int c ) : a ( a ) , b ( b ) , c ( c ) { } } ; double dist ( double x , double y , point p ) { return sqrt ( sq ( x - p . x ) + sq ( y - p . y ) ) ; } double compute ( point p [ ] , int n , line l , double X ) { double res = 0 ; double Y = -1 * ( l . c + l . a * X ) / l . b ; for ( int i = 0 ; i < n ; i ++ ) res += dist ( X , Y , p [ i ] ) ; return res ; } double findOptimumCostUtil ( point p [ ] , int n , line l ) { double low = -1e6 ; double high = 1e6 ; while ( ( high - low ) > EPS ) { double mid1 = low + ( high - low ) / 3 ; double mid2 = high - ( high - low ) / 3 ; double dist1 = compute ( p , n , l , mid1 ) ; double dist2 = compute ( p , n , l , mid2 ) ; if ( dist1 < dist2 ) high = mid2 ; else low = mid1 ; } return compute ( p , n , l , ( low + high ) / 2 ) ; } double findOptimumCost ( int points [ N ] [ 2 ] , line l ) { point p [ N ] ; for ( int i = 0 ; i < N ; i ++ ) p [ i ] = point ( points [ i ] [ 0 ] , points [ i ] [ 1 ] ) ; return findOptimumCostUtil ( p , N , l ) ; } int main ( ) { line l ( 1 , -1 , -3 ) ; int points [ N ] [ 2 ] = { { -3 , -2 } , { -1 , 0 } , { -1 , 2 } , { 1 , 2 } , { 3 , 4 } } ; cout << findOptimumCost ( points , l ) << endl ; return 0 ; } |
Program to find Sum of the series 1 * 3 + 3 * 5 + ... . | C ++ program to find sum of first n terms ; Sn = n * ( 4 * n * n + 6 * n - 1 ) / 3 ; number of terms to be included in the sum ; find the Sn | #include <bits/stdc++.h> NEW_LINE using namespace std ; int calculateSum ( int n ) { return ( n * ( 4 * n * n + 6 * n - 1 ) / 3 ) ; } int main ( ) { int n = 4 ; cout << " Sum β = β " << calculateSum ( n ) ; return 0 ; } |
Find all duplicate and missing numbers in given permutation array of 1 to N | C ++ program for the above approach ; Function to find the duplicate and the missing elements over the range [ 1 , N ] ; Stores the missing and duplicate numbers in the array arr [ ] ; Traverse the given array arr [ ] ; Check if the current element is not same as the element at index arr [ i ] - 1 , then swap ; Otherwise , increment the index ; Traverse the array again ; If the element is not at its correct position ; Stores the missing and the duplicate elements ; Print the Missing Number ; Print the Duplicate Number ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; void findElements ( int arr [ ] , int N ) { int i = 0 ; vector < int > missing ; set < int > duplicate ; set < int > :: iterator it ; while ( i != N ) { cout << i << " β # β " ; if ( arr [ i ] != arr [ arr [ i ] - 1 ] ) { swap ( arr [ i ] , arr [ arr [ i ] - 1 ] ) ; } else { i ++ ; } } for ( i = 0 ; i < N ; i ++ ) { if ( arr [ i ] != i + 1 ) { missing . push_back ( i + 1 ) ; duplicate . insert ( arr [ i ] ) ; } } cout << " Missing β Numbers : β " ; for ( auto & it : missing ) cout << it << ' β ' ; cout << " Duplicate Numbers : " for ( auto & it : duplicate ) cout << it << ' β ' ; } int main ( ) { int arr [ ] = { 1 , 2 , 2 , 2 , 4 , 5 , 7 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; findElements ( arr , N ) ; return 0 ; } |
Triplet with no element divisible by 3 and sum N | C ++ program to print a , b and c such that a + b + c = N ; Function to print a , b and c ; first loop ; check for 1 st number ; second loop ; check for 2 nd number ; third loop ; Check for 3 rd number ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; void printCombination ( int n ) { for ( int i = 1 ; i < n ; i ++ ) { if ( i % 3 != 0 ) { for ( int j = 1 ; j < n ; j ++ ) { if ( j % 3 != 0 ) { for ( int k = 1 ; k < n ; k ++ ) { if ( k % 3 != 0 && ( i + j + k ) == n ) { cout << i << " β " << j << " β " << k ; return ; } } } } } } } int main ( ) { int n = 233 ; printCombination ( n ) ; return 0 ; } |
Program to find the percentage of difference between two numbers | C ++ program to calculate the percentage ; Function to calculate the percentage ; Driver Code . ; Function calling | #include <iostream> NEW_LINE using namespace std ; int percent ( int a , int b ) { float result = 0 ; result = ( ( b - a ) * 100 ) / a ; return result ; } int main ( ) { int a = 20 , b = 25 ; cout << percent ( a , b ) << " % " ; return 0 ; } |
Numbers with sum of digits equal to the sum of digits of its all prime factor | C ++ program to Find the count of the numbers in the given range such that the sum of its digit is equal to the sum of all its prime factors digits sum . ; maximum size of number ; array to store smallest prime factor of number ; array to store sum of digits of a number ; boolean array to check given number is countable for required answer or not . ; prefix array to store answer ; Calculating SPF ( Smallest Prime Factor ) for every number till MAXN . ; marking smallest prime factor for every number to be itself . ; separately marking spf for every even number as 2 ; checking if i is prime ; marking SPF for all numbers divisible by i ; marking spf [ j ] if it is not previously marked ; Function to find sum of digits in a number ; find sum of digits of all numbers up to MAXN ; add sum of digits of least prime factor and n / spf [ n ] ; if it is valid make isValid true ; prefix sum to compute answer ; Driver code ; decleartion ; print answer for required range ; print answer for required range | #include <bits/stdc++.h> NEW_LINE using namespace std ; #define MAXN 100005 NEW_LINE int spf [ MAXN ] = { 0 } ; int sum_digits [ MAXN ] = { 0 } ; bool isValid [ MAXN ] = { 0 } ; int ans [ MAXN ] = { 0 } ; void Smallest_prime_factor ( ) { for ( int i = 1 ; i < MAXN ; i ++ ) spf [ i ] = i ; for ( int i = 4 ; i < MAXN ; i += 2 ) spf [ i ] = 2 ; for ( int i = 3 ; i * i <= MAXN ; i += 2 ) if ( spf [ i ] == i ) for ( int j = i * i ; j < MAXN ; j += i ) if ( spf [ j ] == j ) spf [ j ] = i ; } int Digit_Sum ( int copy ) { int d = 0 ; while ( copy ) { d += copy % 10 ; copy /= 10 ; } return d ; } void Sum_Of_All_Digits ( ) { for ( int n = 2 ; n < MAXN ; n ++ ) { sum_digits [ n ] = sum_digits [ n / spf [ n ] ] + Digit_Sum ( spf [ n ] ) ; if ( Digit_Sum ( n ) == sum_digits [ n ] ) isValid [ n ] = true ; } for ( int n = 2 ; n < MAXN ; n ++ ) { if ( isValid [ n ] ) ans [ n ] = 1 ; ans [ n ] += ans [ n - 1 ] ; } } int main ( ) { Smallest_prime_factor ( ) ; Sum_Of_All_Digits ( ) ; int l , r ; l = 2 , r = 3 ; cout << " Valid β numbers β in β the β range β " << l << " β " << r << " β are β " << ans [ r ] - ans [ l - 1 ] << endl ; l = 2 , r = 10 ; cout << " Valid β numbers β in β the β range β " << l << " β " << r << " β are β " << ans [ r ] - ans [ l - 1 ] << endl ; return 0 ; } |
Count numbers which can be represented as sum of same parity primes | Function to calculate count ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int calculate ( int * array , int size ) { int count = 0 ; for ( int i = 0 ; i < size ; i ++ ) if ( array [ i ] % 2 == 0 && array [ i ] != 0 && array [ i ] != 2 ) count ++ ; return count ; } int main ( ) { int a [ ] = { 1 , 3 , 4 , 6 } ; int size = sizeof ( a ) / sizeof ( a [ 0 ] ) ; cout << calculate ( a , size ) ; } |
N | C ++ program to answer queries for N - th prime factor of a number ; 2 - D vector that stores prime factors ; Function to pre - store prime factors of all numbers till 10 ^ 6 ; calculate unique prime factors for every number till 10 ^ 6 ; find prime factors ; store if prime factor ; Function that returns answer for every query ; Driver Code ; Function to pre - store unique prime factors ; 1 st query ; 2 nd query ; 3 rd query ; 4 th query | #include <bits/stdc++.h> NEW_LINE using namespace std ; const int N = 1000001 ; vector < int > v [ N ] ; void preprocess ( ) { for ( int i = 1 ; i < N ; i ++ ) { int num = i ; for ( int j = 2 ; j <= sqrt ( num ) ; j ++ ) { if ( num % j == 0 ) { v [ i ] . push_back ( j ) ; while ( num % j == 0 ) { num = num / j ; } } } if ( num > 2 ) v [ i ] . push_back ( num ) ; } } int query ( int number , int n ) { return v [ number ] [ n - 1 ] ; } int main ( ) { preprocess ( ) ; int number = 6 , n = 1 ; cout << query ( number , n ) << endl ; number = 210 , n = 3 ; cout << query ( number , n ) << endl ; number = 210 , n = 2 ; cout << query ( number , n ) << endl ; number = 60 , n = 2 ; cout << query ( number , n ) << endl ; return 0 ; } |
Program to find HCF ( Highest Common Factor ) of 2 Numbers | C ++ program to find GCD of two numbers ; Recursive function to return gcd of a and b ; Driver program to test above function | #include <iostream> NEW_LINE using namespace std ; int gcd ( int a , int b ) { if ( b == 0 ) return a ; return gcd ( b , a % b ) ; } int main ( ) { int a = 98 , b = 56 ; cout << " GCD β of β " << a << " β and β " << b << " β is β " << gcd ( a , b ) ; return 0 ; } |
Egg Dropping Puzzle with 2 Eggs and K Floors | CPP program to find optimal number of trials for k floors and 2 eggs . ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int twoEggDrop ( int k ) { return ceil ( ( -1.0 + sqrt ( 1 + 8 * k ) ) / 2.0 ) ; } int main ( ) { int k = 100 ; cout << twoEggDrop ( k ) ; return 0 ; } |
Program to find the Area and Volume of Icosahedron | C ++ program to find the Area and volume of Icosahedron ; Function to find area of Icosahedron ; Formula to calculating area ; Function to find volume of Icosahedron ; Formula to calculating volume ; Driver Code ; Function call to find area of Icosahedron . ; Function call to find volume of Icosahedron . | #include <bits/stdc++.h> NEW_LINE using namespace std ; float findArea ( float a ) { float area ; area = 5 * sqrt ( 3 ) * a * a ; return area ; } float findVolume ( float a ) { float volume ; volume = ( ( float ) 5 / 12 ) * ( 3 + sqrt ( 5 ) ) * a * a * a ; return volume ; } int main ( ) { float a = 5 ; cout << " Area : β " << findArea ( a ) << endl ; cout << " Volume : β " << findVolume ( a ) ; return 0 ; } |
Total number of ways to place X and Y at n places such that no two X are together | C ++ program to find the number of ways Calculate total ways to place ' x ' and ' y ' at n places such that no two ' x ' are together ; Function to return number of ways ; for n = 1 ; for n = 2 ; iterate to find Fibonacci term ; Driver Code ; total number of places | #include <iostream> NEW_LINE using namespace std ; int ways ( int n ) { int first = 2 ; int second = 3 ; int res = 0 ; for ( int i = 3 ; i <= n ; i ++ ) { res = first + second ; first = second ; second = res ; } return res ; } int main ( ) { int n = 7 ; cout << " Total β ways β are β : β " ; cout << ways ( n ) ; return 0 ; } |
Number of digits in N factorial to the power N | CPP program to find count of digits in N factorial raised to N ; we take sum of logarithms as explained in the approach ; multiply the result with n ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int countDigits ( int n ) { double ans = 0 ; for ( int i = 1 ; i <= n ; i ++ ) ans += log10 ( i ) ; ans = ans * n ; return 1 + floor ( ans ) ; } int main ( ) { int n = 4 ; cout << countDigits ( n ) << " STRNEWLINE " ; return 0 ; } |
Program to convert centimeter into meter and kilometer | C ++ program to convert centimeter into meter and kilometer ; Driver Code ; Converting centimeter into meter and kilometer | #include <bits/stdc++.h> NEW_LINE using namespace std ; int main ( ) { float cm , meter , kilometer ; cm = 1000 ; meter = cm / 100.0 ; kilometer = cm / 100000.0 ; cout << " Length β in β meter β = β " << meter << " m " << " STRNEWLINE " ; cout << " Length β in β Kilometer β = β " << kilometer << " km " << " STRNEWLINE " ; return 0 ; } |
Check if two people starting from different points ever meet | C ++ program to find if two people starting from different positions ever meet or not . ; If speed of a person at a position before other person is smaller , then return false . ; Making sure that x1 is greater ; checking if relative speed is a factor of relative distance or not ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; bool everMeet ( int x1 , int x2 , int v1 , int v2 ) { if ( x1 < x2 && v1 <= v2 ) return false ; if ( x1 > x2 && v1 >= v2 ) return false ; if ( x1 < x2 ) { swap ( x1 , x2 ) ; swap ( v1 , v2 ) ; } return ( ( x1 - x2 ) % ( v1 - v2 ) == 0 ) ; } int main ( ) { int x1 = 5 , v1 = 8 , x2 = 4 , v2 = 7 ; if ( everMeet ( x1 , x2 , v1 , v2 ) ) printf ( " Yes " ) ; else printf ( " No " ) ; return 0 ; } |
Count of distinct GCDs among all the non | C ++ program for the above approach ; Function to calculate the number of distinct GCDs among all non - empty subsequences of an array ; variables to store the largest element in array and the required count ; Map to store whether a number is present in A ; calculate largest number in A and mapping A to Mp ; iterate over all possible values of GCD ; variable to check current GCD ; iterate over all multiples of i ; If j is present in A ; calculate gcd of all encountered multiples of i ; current GCD is possible ; return answer ; Driver code ; Input ; Function calling | #include <bits/stdc++.h> NEW_LINE using namespace std ; int distinctGCDs ( int arr [ ] , int N ) { int M = -1 , ans = 0 ; map < int , int > Mp ; for ( int i = 0 ; i < N ; i ++ ) { M = max ( M , arr [ i ] ) ; Mp [ arr [ i ] ] = 1 ; } for ( int i = 1 ; i <= M ; i ++ ) { int currGcd = 0 ; for ( int j = i ; j <= M ; j += i ) { if ( Mp [ j ] ) { currGcd = __gcd ( currGcd , j ) ; if ( currGcd == i ) { ans ++ ; break ; } } } } return ans ; } int main ( ) { int arr [ ] = { 3 , 11 , 14 , 6 , 12 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << distinctGCDs ( arr , N ) << endl ; return 0 ; } |
Find ceil of a / b without using ceil ( ) function | C ++ program to find ceil ( a / b ) without using ceil ( ) function ; Driver function ; taking input 1 ; example of perfect division taking input 2 | #include <cmath> NEW_LINE #include <iostream> NEW_LINE using namespace std ; int main ( ) { int a = 4 ; int b = 3 ; int val = ( a + b - 1 ) / b ; cout << " The β ceiling β value β of β 4/3 β is β " << val << endl ; a = 6 ; b = 3 ; val = ( a + b - 1 ) / b ; cout << " The β ceiling β value β of β 6/3 β is β " << val << endl ; return 0 ; } |
Sum of range in a series of first odd then even natural numbers | CPP program to find sum in the given range in the sequence 1 3 5 7. ... . N 2 4 6. . . N - 1 ; Function that returns sum in the range 1 to x in the sequence 1 3 5 7. ... . N 2 4 6. . . N - 1 ; number of odd numbers ; number of extra even numbers required ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; #define ll long long NEW_LINE ll sumTillX ( ll x , ll n ) { ll odd = ceil ( n / 2.0 ) ; if ( x <= odd ) return x * x ; ll even = x - odd ; return ( ( odd * odd ) + ( even * even ) + even ) ; } int rangeSum ( int N , int L , int R ) { return sumTillX ( R , N ) - sumTillX ( L - 1 , N ) ; } int main ( ) { ll N = 10 , L = 1 , R = 6 ; cout << rangeSum ( N , L , R ) ; return 0 ; } |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.