text
stringlengths 17
4.49k
| code
stringlengths 49
5.46k
|
---|---|
Program to find the length of Latus Rectum of a Parabola | C ++ program for the above approach ; Function to calculate distance between two points ; Calculating distance ; Function to calculate length of the latus rectum of a parabola ; Stores the co - ordinates of the vertex of the parabola ; Stores the co - ordinates of the focus of parabola ; Print the distance between focus and vertex ; Driver Code ; Given a , b & c ; Function call | #include <bits/stdc++.h> NEW_LINE using namespace std ; float distance ( float x1 , float y1 , float x2 , float y2 ) { return sqrt ( ( x2 - x1 ) * ( x2 - x1 ) + ( y2 - y1 ) * ( y2 - y1 ) ) ; } float lengthOfLatusRectum ( float a , float b , float c ) { pair < float , float > vertex = { ( - b / ( 2 * a ) ) , ( ( ( 4 * a * c ) - ( b * b ) ) / ( 4 * a ) ) } ; pair < float , float > focus = { ( - b / ( 2 * a ) ) , ( ( ( 4 * a * c ) - ( b * b ) + 1 ) / ( 4 * a ) ) } ; cout << 4 * distance ( focus . first , focus . second , vertex . first , vertex . second ) ; } int main ( ) { float a = 3 , b = 5 , c = 1 ; lengthOfLatusRectum ( a , b , c ) ; return 0 ; } |
Program to convert polar co | C ++ program for the above approach ; Function to convert degree to radian ; Function to convert the polar coordinate to cartesian ; Convert degerees to radian ; Applying the formula : x = rcos ( theata ) , y = rsin ( theta ) ; Print cartesian coordinates ; Driver Code ; Given polar coordinates ; Function to convert polar coordinates to equivalent cartesian coordinates | #include <bits/stdc++.h> NEW_LINE using namespace std ; double ConvertDegToRad ( double degree ) { double pi = 3.14159 ; return ( degree * ( pi / 180.0 ) ) ; } void ConvertToCartesian ( pair < double , double > polar ) { polar . second = ConvertDegToRad ( polar . second ) ; pair < double , double > cartesian = { polar . first * cos ( polar . second ) , polar . first * sin ( polar . second ) } ; printf ( " % 0.3f , β % 0.3f " , cartesian . first , cartesian . second ) ; } int main ( ) { pair < double , double > polar = { 1.4142 , 45 } ; ConvertToCartesian ( polar ) ; return 0 ; } |
Distance between orthocenter and circumcenter of a right | C ++ program for the above approach ; Function to calculate Euclidean distance between the points p1 and p2 ; Stores x coordinates of both points ; Stores y coordinates of both points ; Return the Euclid distance using distance formula ; Function to find orthocenter of the right angled triangle ; Find the length of the three sides ; Orthocenter will be the vertex opposite to the largest side ; Function to find the circumcenter of right angle triangle ; Circumcenter will be located at center of hypotenuse ; If AB is the hypotenuse ; If BC is the hypotenuse ; If AC is the hypotenuse ; Function to find distance between orthocenter and circumcenter ; Find circumcenter ; Find orthocenter ; Find the distance between the orthocenter and circumcenter ; Print distance between orthocenter and circumcenter ; Driver Code ; Given coordinates A , B , and C ; Function Call | #include <bits/stdc++.h> NEW_LINE using namespace std ; double distance ( pair < double , double > p1 , pair < double , double > p2 ) { double x1 = p1 . first , x2 = p2 . first ; double y1 = p1 . second , y2 = p2 . second ; return sqrt ( pow ( x2 - x1 , 2 ) + pow ( y2 - y1 , 2 ) * 1.0 ) ; } pair < double , double > find_orthocenter ( pair < double , double > A , pair < double , double > B , pair < double , double > C ) { double AB = distance ( A , B ) ; double BC = distance ( B , C ) ; double CA = distance ( C , A ) ; if ( AB > BC && AB > CA ) return C ; if ( BC > AB && BC > CA ) return A ; return B ; } pair < double , double > find_circumcenter ( pair < double , double > A , pair < double , double > B , pair < double , double > C ) { double AB = distance ( A , B ) ; double BC = distance ( B , C ) ; double CA = distance ( C , A ) ; if ( AB > BC && AB > CA ) return { ( A . first + B . first ) / 2 , ( A . second + B . second ) / 2 } ; if ( BC > AB && BC > CA ) return { ( B . first + C . first ) / 2 , ( B . second + C . second ) / 2 } ; return { ( C . first + A . first ) / 2 , ( C . second + A . second ) / 2 } ; } void findDistance ( pair < double , double > A , pair < double , double > B , pair < double , double > C ) { pair < double , double > circumcenter = find_circumcenter ( A , B , C ) ; pair < double , double > orthocenter = find_orthocenter ( A , B , C ) ; double distance_between = distance ( circumcenter , orthocenter ) ; cout << distance_between << endl ; } int main ( ) { pair < double , double > A , B , C ; A = { 0.0 , 0.0 } ; B = { 6.0 , 0.0 } ; C = { 0.0 , 8.0 } ; findDistance ( A , B , C ) ; return 0 ; } |
Generate all integral points lying inside a rectangle | C ++ program to implement the above approach ; Function to generate coordinates lying within the rectangle ; Store all possible coordinates that lie within the rectangle ; Stores the number of possible coordinates that lie within the rectangle ; Use current time as seed for random generator ; Generate all possible coordinates ; Generate all possible X - coordinates ; Generate all possible Y - coordinates ; If coordinates ( X , Y ) has not been generated already ; Insert the coordinates ( X , Y ) ; Print the coordinates ; Driver Code ; Rectangle dimensions | #include <bits/stdc++.h> NEW_LINE using namespace std ; void generatePoints ( int L , int W ) { set < pair < int , int > > hash ; int total = ( L * W ) ; srand ( time ( 0 ) ) ; while ( total -- ) { int X = rand ( ) % L ; int Y = rand ( ) % W ; while ( hash . count ( { X , Y } ) ) { X = rand ( ) % L ; Y = rand ( ) % W ; } hash . insert ( { X , Y } ) ; } for ( auto points : hash ) { cout << " ( " << points . first << " , β " << points . second << " ) β " ; } } int main ( ) { int L = 3 , W = 2 ; generatePoints ( L , W ) ; } |
Count triangles required to form a House of Cards of height N | C ++ implementation of the above approach ; Function to find the number of triangles ; Driver Code ; Function call | #include <bits/stdc++.h> NEW_LINE using namespace std ; int noOfTriangles ( int n ) { return floor ( n * ( n + 2 ) * ( 2 * n + 1 ) / 8 ) ; } int main ( ) { int n = 3 ; cout << noOfTriangles ( n ) << endl ; return 0 ; } |
Check if N contains all digits as K in base B | C ++ implementation of the approach ; Function to print the number of digits ; Calculate log using base change property and then take its floor and then add 1 ; Return the output ; Function that returns true if n contains all one 's in base b ; Calculate the sum ; Driver code ; Given number N ; Given base B ; Given digit K ; Function call | #include <bits/stdc++.h> NEW_LINE using namespace std ; int findNumberOfDigits ( int n , int base ) { int dig = ( floor ( log ( n ) / log ( base ) ) + 1 ) ; return ( dig ) ; } int isAllKs ( int n , int b , int k ) { int len = findNumberOfDigits ( n , b ) ; int sum = k * ( 1 - pow ( b , len ) ) / ( 1 - b ) ; if ( sum == n ) { return ( sum ) ; } } int main ( ) { int N = 13 ; int B = 3 ; int K = 1 ; if ( isAllKs ( N , B , K ) ) { cout << " Yes " ; } else { cout << " No " ; } } |
Check if a right | C ++ program to implement the above approach ; Function to check if right - angled triangle can be formed by the given coordinates ; Calculate the sides ; Check Pythagoras Formula ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; void checkRightAngled ( int X1 , int Y1 , int X2 , int Y2 , int X3 , int Y3 ) { int A = ( int ) pow ( ( X2 - X1 ) , 2 ) + ( int ) pow ( ( Y2 - Y1 ) , 2 ) ; int B = ( int ) pow ( ( X3 - X2 ) , 2 ) + ( int ) pow ( ( Y3 - Y2 ) , 2 ) ; int C = ( int ) pow ( ( X3 - X1 ) , 2 ) + ( int ) pow ( ( Y3 - Y1 ) , 2 ) ; if ( ( A > 0 and B > 0 and C > 0 ) and ( A == ( B + C ) or B == ( A + C ) or C == ( A + B ) ) ) cout << " Yes " ; else cout << " No " ; } int main ( ) { int X1 = 0 , Y1 = 2 ; int X2 = 0 , Y2 = 14 ; int X3 = 9 , Y3 = 2 ; checkRightAngled ( X1 , Y1 , X2 , Y2 , X3 , Y3 ) ; return 0 ; } |
Count of intersections of M line segments with N vertical lines in XY plane | C ++ implementation for the above approach . ; Function to create prefix sum array ; Initialize the prefix array to remove garbage values ; Marking the occurences of vertical lines ; x is the value after Index mapping ; Creating the prefix array ; Function returns the count of total intersection ; ans is the number of points of intersection of the line segments with the vertical lines ; Index mapping ; We don 't consider a vertical line segment because even if it falls on a verticale line then it just touches it and not intersects. ; We have assumed that x1 will be left and x2 right but if not then we just swap them ; Driver code ; N is the number of vertical lines M is the number of line segments ; Format : x1 , y1 , x2 , y1 ; First create the prefix array ; Print the total number of intersections | #include <bits/stdc++.h> NEW_LINE using namespace std ; void createPrefixArray ( int n , int arr [ ] , int prefSize , int pref [ ] ) { for ( int i = 0 ; i < prefSize ; i ++ ) { pref [ i ] = 0 ; } for ( int i = 0 ; i < n ; i ++ ) { int x = arr [ i ] + 1000000 ; pref [ x ] ++ ; } for ( int i = 1 ; i < prefSize ; i ++ ) { pref [ i ] += pref [ i - 1 ] ; } } int pointsOfIntersection ( int m , int segments [ ] [ 4 ] , int size , int pref [ ] ) { int ans = 0 ; for ( int i = 0 ; i < m ; i ++ ) { int x1 = segments [ i ] [ 0 ] ; int x2 = segments [ i ] [ 2 ] ; x1 = x1 + 1000000 ; x2 = x2 + 1000000 ; if ( x1 != x2 ) { if ( x1 > x2 ) { swap ( x1 , x2 ) ; } int Occ_Till_Right = pref [ x2 - 1 ] ; int Occ_Till_Left = pref [ x1 ] ; ans = ans + ( Occ_Till_Right - Occ_Till_Left ) ; } } return ans ; } int main ( ) { int N = 4 ; int M = 8 ; int size = 2000000 + 2 ; int pref [ size ] ; int lines [ N ] = { -5 , -3 , 2 , 3 } ; int segments [ M ] [ 4 ] = { { -2 , 5 , 5 , -6 } , { -5 , -2 , -3 , -5 } , { -2 , 3 , -6 , 1 } , { -1 , -3 , 4 , 2 } , { 2 , 5 , 2 , 1 } , { 4 , 5 , 4 , -5 } , { -2 , -4 , 5 , 3 } , { 1 , 2 , -2 , 1 } } ; createPrefixArray ( N , lines , size , pref ) ; cout << pointsOfIntersection ( M , segments , size , pref ) << endl ; return 0 ; } |
Count of rectangles possible from N and M straight lines parallel to X and Y axis respectively | C ++ Program to count number of rectangles formed by N lines parallel to X axis M lines parallel to Y axis ; Function to calculate number of rectangles ; Total number of ways to select two lines parallel to X axis ; Total number of ways to select two lines parallel to Y axis ; Total number of rectangles ; Driver Program | #include <bits/stdc++.h> NEW_LINE using namespace std ; int count_rectangles ( int N , int M ) { int p_x = ( N * ( N - 1 ) ) / 2 ; int p_y = ( M * ( M - 1 ) ) / 2 ; return p_x * p_y ; } int main ( ) { int N = 3 ; int M = 6 ; cout << count_rectangles ( N , M ) ; } |
Angle between a Pair of Lines in 3D | C ++ program for the above approach ; Function to find the angle between the two lines ; Find direction ratio of line AB ; Find direction ratio of line BC ; Find the dotProduct of lines AB & BC ; Find magnitude of line AB and BC ; Find the cosine of the angle formed by line AB and BC ; Find angle in radian ; Print the angle ; Driver Code ; Given coordinates Points A ; Points B ; Points C ; Function Call | #include " bits / stdc + + . h " NEW_LINE #define PI 3.14 NEW_LINE using namespace std ; void calculateAngle ( int x1 , int y1 , int z1 , int x2 , int y2 , int z2 , int x3 , int y3 , int z3 ) { int ABx = x1 - x2 ; int ABy = y1 - y2 ; int ABz = z1 - z2 ; int BCx = x3 - x2 ; int BCy = y3 - y2 ; int BCz = z3 - z2 ; double dotProduct = ABx * BCx + ABy * BCy + ABz * BCz ; double magnitudeAB = ABx * ABx + ABy * ABy + ABz * ABz ; double magnitudeBC = BCx * BCx + BCy * BCy + BCz * BCz ; double angle = dotProduct ; angle /= sqrt ( magnitudeAB * magnitudeBC ) ; angle = ( angle * 180 ) / PI ; cout << abs ( angle ) << endl ; } int main ( ) { int x1 = 1 , y1 = 3 , z1 = 3 ; int x2 = 3 , y2 = 4 , z2 = 5 ; int x3 = 5 , y3 = 6 , z3 = 9 ; calculateAngle ( x1 , y1 , z1 , x2 , y2 , z2 , x3 , y3 , z3 ) ; return 0 ; } |
Distance between end points of Hour and minute hand at given time | C ++ implementation to find the distance between the end points of the hour and minute hand ; Function to find the angle between Hour hand and minute hand ; Validate the input ; Calculate the angles moved by hour and minute hands with reference to 12 : 00 ; Find the difference between two angles ; Return the smaller angle of two possible angles ; Function to calculate cos value of angle c ; Converting degrees to radian ; Maps the sum along the series ; Holds the actual value of sin ( n ) ; Function to distance between the endpoints of the hour and minute hand ; Driver Code ; Time ; Length of hour hand ; Length of minute hand ; calling Function for finding angle between hour hand and minute hand ; Function for finding distance between end points of minute hand and hour hand | #include <bits/stdc++.h> NEW_LINE using namespace std ; int calcAngle ( double h , double m ) { if ( h < 0 m < 0 h > 12 m > 60 ) printf ( " Wrong β input " ) ; if ( h == 12 ) h = 0 ; if ( m == 60 ) m = 0 ; int hour_angle = 0.5 * ( h * 60 + m ) ; int minute_angle = 6 * m ; int angle = abs ( hour_angle - minute_angle ) ; angle = min ( 360 - angle , angle ) ; return angle ; } float cal_cos ( float n ) { float accuracy = 0.0001 , x1 , denominator , cosx , cosval ; n = n * ( 3.142 / 180.0 ) ; x1 = 1 ; cosx = x1 ; cosval = cos ( n ) ; int i = 1 ; do { denominator = 2 * i * ( 2 * i - 1 ) ; x1 = - x1 * n * n / denominator ; cosx = cosx + x1 ; i = i + 1 ; } while ( accuracy <= fabs ( cosval - cosx ) ) ; return cosx ; } float distanceEndpoints ( int a , int b , float c ) { float angle = cal_cos ( c ) ; return sqrt ( ( a * a ) + ( b * b ) - 2 * a * b * angle ) ; } int main ( ) { int hour = 3 ; int min = 30 ; int hourHand = 3 ; int minHand = 4 ; double angle = calcAngle ( hour , min ) ; float distance = distanceEndpoints ( minHand , hourHand , angle ) ; cout << distance ; return 0 ; } |
Pentadecagonal Number | C ++ program to find Nth Pentadecagonal number ; Function to find N - th Pentadecagonal number ; Formula to calculate nth Pentadecagonal number ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int Pentadecagonal_num ( int n ) { return ( 13 * n * n - 11 * n ) / 2 ; } int main ( ) { int n = 3 ; cout << Pentadecagonal_num ( n ) << endl ; n = 10 ; cout << Pentadecagonal_num ( n ) << endl ; return 0 ; } |
Octadecagonal Number | C ++ program to find Nth Octadecagonal number ; Function to find N - th Octadecagonal number ; Formula to calculate nth Octadecagonal number ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int Octadecagonal_num ( int n ) { return ( 16 * n * n - 14 * n ) / 2 ; } int main ( ) { int n = 3 ; cout << Octadecagonal_num ( n ) << endl ; n = 10 ; cout << Octadecagonal_num ( n ) << endl ; return 0 ; } |
Icositrigonal Number | C ++ program to find nth Icositrigonal number ; Function to find N - th Icositrigonal number ; Formula to calculate nth Icositrigonal number ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int Icositrigonal_num ( int n ) { return ( 21 * n * n - 19 * n ) / 2 ; } int main ( ) { int n = 3 ; cout << Icositrigonal_num ( n ) << endl ; n = 10 ; cout << Icositrigonal_num ( n ) ; return 0 ; } |
Find the percentage change in the area of a Rectangle | CPP implementation to find the percentage ; Function to calculate percentage change in area of rectangle ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int calculate_change ( int length , int breadth ) { int change = 0 ; change = length + breadth + ( ( length * breadth ) / 100 ) ; return change ; } int main ( ) { int cL = 20 ; int cB = -10 ; int cA = calculate_change ( cL , cB ) ; printf ( " % d " , cA ) ; return 0 ; } |
Minimum number of Circular obstacles required to obstruct the path in a Grid | C ++ program to find the minimum number of obstacles required ; Function to find the minimum number of obstacles required ; Find the minimum range required to put obstacles ; Sorting the radius ; If val is less than zero then we have find the number of obstacles required ; Driver function | #include <bits/stdc++.h> NEW_LINE using namespace std ; int solve ( int n , int m , int obstacles , double range [ ] ) { double val = min ( n , m ) ; sort ( range , range + obstacles ) ; int c = 1 ; for ( int i = obstacles - 1 ; i >= 0 ; i -- ) { range [ i ] = 2 * range [ i ] ; val -= range [ i ] ; if ( val <= 0 ) { return c ; } else { c ++ ; } } if ( val > 0 ) { return -1 ; } } int main ( ) { int n = 4 , m = 5 , obstacles = 3 ; double range [ ] = { 1.0 , 1.25 , 1.15 } ; cout << solve ( n , m , obstacles , range ) << " STRNEWLINE " ; return 0 ; } |
Program to calculate area of a rhombus whose one side and diagonal are given | C ++ program to calculate the area of a rhombus whose one side and one diagonal is given ; function to calculate the area of the rhombus ; Second diagonal ; area of rhombus ; return the area ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; double area ( double d1 , double a ) { double d2 = sqrt ( 4 * ( a * a ) - d1 * d1 ) ; double area = 0.5 * d1 * d2 ; return area ; } int main ( ) { double d = 7.07 ; double a = 5 ; printf ( " % 0.8f " , area ( d , a ) ) ; } |
Check whether two points ( x1 , y1 ) and ( x2 , y2 ) lie on same side of a given line or not | C ++ program to check if two points lie on the same side or not ; Function to check if two points lie on the same side or not ; int fx1 ; Variable to store a * x1 + b * y1 - c int fx2 ; Variable to store a * x2 + b * y2 - c ; If fx1 and fx2 have same sign ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; bool pointsAreOnSameSideOfLine ( int a , int b , int c , int x1 , int y1 , int x2 , int y2 ) { fx1 = a * x1 + b * y1 - c ; fx2 = a * x2 + b * y2 - c ; if ( ( fx1 * fx2 ) > 0 ) return true ; return false ; } int main ( ) { int a = 1 , b = 1 , c = 1 ; int x1 = 1 , y1 = 1 ; int x2 = 2 , y2 = 1 ; if ( pointsAreOnSameSideOfLine ( a , b , c , x1 , y1 , x2 , y2 ) ) cout << " Yes " ; else cout << " No " ; } |
Percentage increase in volume of the cube if a side of cube is increased by a given percentage | C ++ program to find percentage increase in the volume of the cube if a side of cube is increased by a given percentage ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; void newvol ( double x ) { cout << " percentage β increase β " << " in β the β volume β of β the β cube β is β " << pow ( x , 3 ) / 10000 + 3 * x + ( 3 * pow ( x , 2 ) ) / 100 << " % " << endl ; } int main ( ) { double x = 10 ; newvol ( x ) ; return 0 ; } |
Number of triangles formed by joining vertices of n | C ++ program to implement the above problem ; Function to find the number of triangles ; print the number of triangles having two side common ; print the number of triangles having no side common ; Driver code ; initialize the number of sides of a polygon | #include <bits/stdc++.h> NEW_LINE using namespace std ; void findTriangles ( int n ) { int num = n ; cout << num << " β " ; cout << num * ( num - 4 ) * ( num - 5 ) / 6 ; } int main ( ) { int n ; n = 6 ; findTriangles ( n ) ; return 0 ; } |
Find the radii of the circles which are lined in a row , and distance between the centers of first and last circle is given | C ++ program to find radii of the circles which are lined in a row and distance between the centers of first and last circle is given ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; void radius ( int n , int d ) { cout << " The β radius β of β each β circle β is β " << d / ( 2 * n - 2 ) << endl ; } int main ( ) { int d = 42 , n = 4 ; radius ( n , d ) ; return 0 ; } |
Find the side of the squares which are lined in a row , and distance between the centers of first and last square is given | C ++ program to find side of the squares which are lined in a row and distance between the centers of first and last squares is given ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; void radius ( int n , int d ) { cout << " The β side β of β each β square β is β " << d / ( n - 1 ) << endl ; } int main ( ) { int d = 42 , n = 4 ; radius ( n , d ) ; return 0 ; } |
Number of triangles formed by joining vertices of n | C ++ program to implement the above problem ; Function to find the number of triangles ; print the number of triangles ; Driver code ; initialize the number of sides of a polygon | #include <bits/stdc++.h> NEW_LINE using namespace std ; void findTriangles ( int n ) { int num ; num = n * ( n - 4 ) ; cout << num ; } int main ( ) { int n ; n = 6 ; findTriangles ( n ) ; return 0 ; } |
Find the Diameter or Longest chord of a Circle | C ++ program to find the longest chord or diameter of the circle whose radius is given ; Function to find the longest chord ; Driver code ; Get the radius ; Find the diameter | #include <bits/stdc++.h> NEW_LINE using namespace std ; void diameter ( double r ) { cout << " The β length β of β the β longest β chord " << " β or β diameter β of β the β circle β is β " << 2 * r << endl ; } int main ( ) { double r = 4 ; diameter ( r ) ; return 0 ; } |
Slope of the line parallel to the line with the given slope | C ++ implementation of the approach ; Function to return the slope of the line which is parallel to the line with the given slope ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; double getSlope ( double m ) { return m ; } int main ( ) { double m = 2 ; cout << getSlope ( m ) ; return 0 ; } |
Total number of triangles formed when there are H horizontal and V vertical lines | C ++ implementation of the approach ; Function to return total triangles ; Only possible triangle is the given triangle ; If only vertical lines are present ; If only horizontal lines are present ; Return total triangles ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; #define LLI long long int NEW_LINE LLI totalTriangles ( LLI h , LLI v ) { if ( h == 0 && v == 0 ) return 1 ; if ( h == 0 ) return ( ( v + 1 ) * ( v + 2 ) / 2 ) ; if ( v == 0 ) return ( h + 1 ) ; LLI Total = ( h + 1 ) * ( ( v + 1 ) * ( v + 2 ) / 2 ) ; return Total ; } int main ( ) { int h = 2 , v = 2 ; cout << totalTriangles ( h , v ) ; return 0 ; } |
Largest sphere that can be inscribed in a right circular cylinder inscribed in a frustum | C ++ Program to find the biggest sphere that can be inscribed within a right circular cylinder which in turn is inscribed within a frustum ; Function to find the biggest sphere ; the radii and height cannot be negative ; radius of the sphere ; volume of the sphere ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; float sph ( float r , float R , float h ) { if ( r < 0 && R < 0 && h < 0 ) return -1 ; float x = r ; float V = ( 4 * 3.14 * pow ( r , 3 ) ) / 3 ; return V ; } int main ( ) { float r = 5 , R = 8 , h = 11 ; cout << sph ( r , R , h ) << endl ; return 0 ; } |
Check whether two straight lines are orthogonal or not | C ++ implementation of above approach ; Function to check if two straight lines are orthogonal or not ; Both lines have infinite slope ; Only line 1 has infinite slope ; Only line 2 has infinite slope ; Find slopes of the lines ; Check if their product is - 1 ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; bool checkOrtho ( int x1 , int y1 , int x2 , int y2 , int x3 , int y3 , int x4 , int y4 ) { int m1 , m2 ; if ( x2 - x1 == 0 && x4 - x3 == 0 ) return false ; else if ( x2 - x1 == 0 ) { m2 = ( y4 - y3 ) / ( x4 - x3 ) ; if ( m2 == 0 ) return true ; else return false ; } else if ( x4 - x3 == 0 ) { m1 = ( y2 - y1 ) / ( x2 - x1 ) ; if ( m1 == 0 ) return true ; else return false ; } else { m1 = ( y2 - y1 ) / ( x2 - x1 ) ; m2 = ( y4 - y3 ) / ( x4 - x3 ) ; if ( m1 * m2 == -1 ) return true ; else return false ; } } int main ( ) { int x1 = 0 , y1 = 4 , x2 = 0 , y2 = -9 ; int x3 = 2 , y3 = 0 , x4 = -1 , y4 = 0 ; checkOrtho ( x1 , y1 , x2 , y2 , x3 , y3 , x4 , y4 ) ? cout << " Yes " : cout << " No " ; return 0 ; } |
Diagonal of a Regular Pentagon | C ++ Program to find the diagonal of a regular pentagon ; Function to find the diagonal of a regular pentagon ; Side cannot be negative ; Length of the diagonal ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; float pentdiagonal ( float a ) { if ( a < 0 ) return -1 ; float d = 1.22 * a ; return d ; } int main ( ) { float a = 6 ; cout << pentdiagonal ( a ) << endl ; return 0 ; } |
Area of hexagon with given diagonal length | C ++ program to find the area of Hexagon with given diagonal ; Function to calculate area ; Formula to find area ; Main | #include <bits/stdc++.h> NEW_LINE using namespace std ; float hexagonArea ( float d ) { return ( 3 * sqrt ( 3 ) * pow ( d , 2 ) ) / 8 ; } int main ( ) { float d = 10 ; cout << " Area β of β hexagon : β " << hexagonArea ( d ) ; return 0 ; } |
Number of squares of side length required to cover an N * M rectangle | CPP program to find number of squares of a * a required to cover n * m rectangle ; function to find number of squares of a * a required to cover n * m rectangle ; Driver code ; function call | #include <bits/stdc++.h> NEW_LINE using namespace std ; int Squares ( int n , int m , int a ) { return ( ( m + a - 1 ) / a ) * ( ( n + a - 1 ) / a ) ; } int main ( ) { int n = 6 , m = 6 , a = 4 ; cout << Squares ( n , m , a ) ; return 0 ; } |
Length of the Diagonal of the Octagon | C ++ Program to find the diagonal of the octagon ; Function to find the diagonal of the octagon ; side cannot be negative ; diagonal of the octagon ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; float octadiagonal ( float a ) { if ( a < 0 ) return -1 ; return a * sqrt ( 4 + ( 2 * sqrt ( 2 ) ) ) ; } int main ( ) { float a = 4 ; cout << octadiagonal ( a ) << endl ; return 0 ; } |
Program to Calculate the Perimeter of a Decagon | C ++ program to Calculate the Perimeter of a Decagon ; Function for finding the perimeter ; Driver code | #include <iostream> NEW_LINE using namespace std ; void CalPeri ( ) { int s = 5 , Perimeter ; Perimeter = 10 * s ; cout << " The β Perimeter β of β Decagon β is β : β " << Perimeter ; } int main ( ) { CalPeri ( ) ; return 0 ; } |
Sum of lengths of all 12 edges of any rectangular parallelepiped | C ++ program to illustrate the above problem ; function to find the sum of all the edges of parallelepiped ; to calculate the length of one edge ; sum of all the edges of one side ; net sum will be equal to the summation of edges of all the sides ; Driver code ; initialize the area of three faces which has a common vertex | #include <bits/stdc++.h> NEW_LINE using namespace std ; double findEdges ( double s1 , double s2 , double s3 ) { double a = sqrt ( s1 * s2 / s3 ) ; double b = sqrt ( s3 * s1 / s2 ) ; double c = sqrt ( s3 * s2 / s1 ) ; double sum = a + b + c ; return 4 * sum ; } int main ( ) { double s1 , s2 , s3 ; s1 = 65 , s2 = 156 , s3 = 60 ; cout << findEdges ( s1 , s2 , s3 ) ; return 0 ; } |
Maximum number of pieces in N cuts | C ++ program to find maximum no of pieces by given number of cuts ; Function for finding maximum pieces with n cuts . ; to maximize number of pieces x is the horizontal cuts ; Now ( x ) is the horizontal cuts and ( n - x ) is vertical cuts , then maximum number of pieces = ( x + 1 ) * ( n - x + 1 ) ; Driver code ; Taking the maximum number of cuts allowed as 3 ; Finding and printing the max number of pieces | #include <bits/stdc++.h> NEW_LINE using namespace std ; int findMaximumPieces ( int n ) { int x = n / 2 ; return ( ( x + 1 ) * ( n - x + 1 ) ) ; } int main ( ) { int n = 3 ; cout << " Max β number β of β pieces β for β n β = β " << n << " β is β " << findMaximumPieces ( 3 ) ; return 0 ; } |
Program to check whether 4 points in a 3 | C ++ program to check if 4 points in a 3 - D plane are Coplanar ; Function to find equation of plane . ; checking if the 4 th point satisfies the above equation ; Driver Code ; function calling | #include <bits/stdc++.h> NEW_LINE using namespace std ; void equation_plane ( int x1 , int y1 , int z1 , int x2 , int y2 , int z2 , int x3 , int y3 , int z3 , int x , int y , int z ) { int a1 = x2 - x1 ; int b1 = y2 - y1 ; int c1 = z2 - z1 ; int a2 = x3 - x1 ; int b2 = y3 - y1 ; int c2 = z3 - z1 ; int a = b1 * c2 - b2 * c1 ; int b = a2 * c1 - a1 * c2 ; int c = a1 * b2 - b1 * a2 ; int d = ( - a * x1 - b * y1 - c * z1 ) ; if ( a * x + b * y + c * z + d == 0 ) cout << " Coplanar " << endl ; else cout << " Not β Coplanar " << endl ; } int main ( ) { int x1 = 3 ; int y1 = 2 ; int z1 = -5 ; int x2 = -1 ; int y2 = 4 ; int z2 = -3 ; int x3 = -3 ; int y3 = 8 ; int z3 = -5 ; int x4 = -3 ; int y4 = 2 ; int z4 = 1 ; equation_plane ( x1 , y1 , z1 , x2 , y2 , z2 , x3 , y3 , z3 , x4 , y4 , z4 ) ; return 0 ; } |
Angle between two Planes in 3D | C ++ program to find the Angle between two Planes in 3 D . ; Function to find Angle ; Driver Code | #include <bits/stdc++.h> NEW_LINE #include <math.h> NEW_LINE using namespace std ; void distance ( float a1 , float b1 , float c1 , float a2 , float b2 , float c2 ) { float d = ( a1 * a2 + b1 * b2 + c1 * c2 ) ; float e1 = sqrt ( a1 * a1 + b1 * b1 + c1 * c1 ) ; float e2 = sqrt ( a2 * a2 + b2 * b2 + c2 * c2 ) ; d = d / ( e1 * e2 ) ; float pi = 3.14159 ; float A = ( 180 / pi ) * ( acos ( d ) ) ; cout << " Angle β is β " << A << " β degree " ; } int main ( ) { float a1 = 1 ; float b1 = 1 ; float c1 = 2 ; float d1 = 1 ; float a2 = 2 ; float b2 = -1 ; float c2 = 1 ; float d2 = -4 ; distance ( a1 , b1 , c1 , a2 , b2 , c2 ) ; return 0 ; } |
Mirror of a point through a 3 D plane | C ++ program to find Mirror of a point through a 3 D plane ; Function to mirror image ; Driver Code ; function call | #include <bits/stdc++.h> NEW_LINE #include <math.h> NEW_LINE #include <iostream> NEW_LINE #include <iomanip> NEW_LINE using namespace std ; void mirror_point ( float a , float b , float c , float d , float x1 , float y1 , float z1 ) { float k = ( - a * x1 - b * y1 - c * z1 - d ) / ( float ) ( a * a + b * b + c * c ) ; float x2 = a * k + x1 ; float y2 = b * k + y1 ; float z2 = c * k + z1 ; float x3 = 2 * x2 - x1 ; float y3 = 2 * y2 - y1 ; float z3 = 2 * z2 - z1 ; std :: cout << std :: fixed ; std :: cout << std :: setprecision ( 1 ) ; cout << " β x3 β = β " << x3 ; cout << " β y3 β = β " << y3 ; cout << " β z3 β = β " << z3 ; } int main ( ) { float a = 1 ; float b = -2 ; float c = 0 ; float d = 0 ; float x1 = -1 ; float y1 = 3 ; float z1 = 4 ; mirror_point ( a , b , c , d , x1 , y1 , z1 ) ; return 0 ; } |
Number of rectangles in a circle of radius R | C ++ program to find the number of rectangles that can be cut from a circle of Radius R ; Function to return the total possible rectangles that can be cut from the circle ; Diameter = 2 * Radius ; Square of diameter which is the square of the maximum length diagonal ; generate all combinations of a and b in the range ( 1 , ( 2 * Radius - 1 ) ) ( Both inclusive ) ; Calculate the Diagonal length of this rectangle ; If this rectangle 's Diagonal Length is less than the Diameter, it is a valid rectangle, thus increment counter ; Driver Code ; Radius of the circle | #include <bits/stdc++.h> NEW_LINE using namespace std ; int countRectangles ( int radius ) { int rectangles = 0 ; int diameter = 2 * radius ; int diameterSquare = diameter * diameter ; for ( int a = 1 ; a < 2 * radius ; a ++ ) { for ( int b = 1 ; b < 2 * radius ; b ++ ) { int diagonalLengthSquare = ( a * a + b * b ) ; if ( diagonalLengthSquare <= diameterSquare ) { rectangles ++ ; } } } return rectangles ; } int main ( ) { int radius = 2 ; int totalRectangles ; totalRectangles = countRectangles ( radius ) ; cout << totalRectangles << " β rectangles β can β be " << " cut β from β a β circle β of β Radius β " << radius ; return 0 ; } |
Program to check similarity of given two triangles | C ++ program to check similarity between two triangles . ; Function for AAA similarity ; Check for AAA ; Function for SAS similarity ; angle b / w two smallest sides is largest . ; since we take angle b / w the sides . ; Function for SSS similarity ; Check for SSS ; Driver Code ; function call for AAA similarity ; function call for SSS similarity ; function call for SAS similarity ; Check if triangles are similar or not | #include <bits/stdc++.h> NEW_LINE using namespace std ; int simi_aaa ( int a1 [ ] , int a2 [ ] ) { sort ( a1 , a1 + 3 ) ; sort ( a2 , a2 + 3 ) ; if ( a1 [ 0 ] == a2 [ 0 ] && a1 [ 1 ] == a2 [ 1 ] && a1 [ 2 ] == a2 [ 2 ] ) return 1 ; else return 0 ; } int simi_sas ( int s1 [ ] , int s2 [ ] , int a1 [ ] , int a2 [ ] ) { sort ( a1 , a1 + 3 ) ; sort ( a2 , a2 + 3 ) ; sort ( s1 , s1 + 3 ) ; sort ( s2 , s2 + 3 ) ; if ( s1 [ 0 ] / s2 [ 0 ] == s1 [ 1 ] / s2 [ 1 ] ) { if ( a1 [ 2 ] == a2 [ 2 ] ) return 1 ; } if ( s1 [ 1 ] / s2 [ 1 ] == s1 [ 2 ] / s2 [ 2 ] ) { if ( a1 [ 0 ] == a2 [ 0 ] ) return 1 ; } if ( s1 [ 2 ] / s2 [ 2 ] == s1 [ 0 ] / s2 [ 0 ] ) { if ( a1 [ 1 ] == a2 [ 1 ] ) return 1 ; } return 0 ; } int simi_sss ( int s1 [ ] , int s2 [ ] ) { sort ( s1 , s1 + 3 ) ; sort ( s2 , s2 + 3 ) ; if ( s1 [ 0 ] / s2 [ 0 ] == s1 [ 1 ] / s2 [ 1 ] && s1 [ 1 ] / s2 [ 1 ] == s1 [ 2 ] / s2 [ 2 ] && s1 [ 2 ] / s2 [ 2 ] == s1 [ 0 ] / s2 [ 0 ] ) return 1 ; return 0 ; } int main ( ) { int s1 [ ] = { 2 , 3 , 3 } ; int s2 [ ] = { 4 , 6 , 6 } ; int a1 [ ] = { 80 , 60 , 40 } ; int a2 [ ] = { 40 , 60 , 80 } ; int aaa = simi_aaa ( a1 , a2 ) ; int sss = simi_sss ( s1 , s2 ) ; int sas = simi_sas ( s1 , s2 , a1 , a2 ) ; if ( aaa == 1 sss == 1 sas == 1 ) { cout << " Triangles β are β " << " similar β by β " ; if ( aaa == 1 ) cout << " AAA β " ; if ( sss == 1 ) cout << " SSS β " ; if ( sas == 1 ) cout << " SAS . " ; } else cout << " Triangles β are β " << " not β similar " ; return 0 ; } |
Centered Pentadecagonal Number | C ++ Program to find nth centered pentadecagonal number ; centered pentadecagonal function ; Formula to calculate nth centered pentadecagonal number ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int center_pentadecagonal_num ( long int n ) { return ( 15 * n * n - 15 * n + 2 ) / 2 ; } int main ( ) { long int n = 3 ; cout << n << " th β number β : β " << center_pentadecagonal_num ( n ) ; cout << endl ; n = 10 ; cout << n << " th β number β : β " << center_pentadecagonal_num ( n ) ; return 0 ; } |
Centered nonadecagonal number | C ++ Program to find nth centered nonadecagonal number ; centered nonadecagonal function ; Formula to calculate nth centered nonadecagonal number ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int center_nonadecagon_num ( long int n ) { return ( 19 * n * n - 19 * n + 2 ) / 2 ; } int main ( ) { long int n = 2 ; cout << n << " th β centered β nonadecagonal β number β : β " << center_nonadecagon_num ( n ) ; cout << endl ; n = 7 ; cout << n << " th β centered β nonadecagonal β number β : β " << center_nonadecagon_num ( n ) ; return 0 ; } |
Hendecagonal number | C ++ program to find nth Hendecagonal number ; Function to find Hendecagonal number ; Formula to calculate nth Hendecagonal number ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int hendecagonal_num ( int n ) { return ( 9 * n * n - 7 * n ) / 2 ; } int main ( ) { int n = 3 ; cout << n << " rd β Hendecagonal β number : β " ; cout << hendecagonal_num ( n ) ; cout << endl ; n = 10 ; cout << n << " th β Hendecagonal β number : β " ; cout << hendecagonal_num ( n ) ; return 0 ; } |
Centered Octagonal Number | Program to find nth centered octagonal number ; Centered octagonal number function ; Formula to calculate nth centered octagonal number & return it into main function . ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int cen_octagonalnum ( long int n ) { return ( 4 * n * n - 4 * n + 1 ) ; } int main ( ) { long int n = 6 ; cout << n << " th β centered " << " β octagonal β number β : β " ; cout << cen_octagonalnum ( n ) ; cout << endl ; n = 11 ; cout << n << " th β centered " << " β octagonal β number β : β " ; cout << cen_octagonalnum ( n ) ; return 0 ; } |
Number of ordered points pair satisfying line equation | CPP code to count the number of ordered pairs satisfying Line Equation ; Checks if ( i , j ) is valid , a point ( i , j ) is valid if point ( arr [ i ] , arr [ j ] ) satisfies the equation y = mx + c And i is not equal to j ; check if i equals to j ; Equation LHS = y , and RHS = mx + c ; Returns the number of ordered pairs ( i , j ) for which point ( arr [ i ] , arr [ j ] ) satisfies the equation of the line y = mx + c ; for every possible ( i , j ) check if ( a [ i ] , a [ j ] ) satisfies the equation y = mx + c ; ( firstIndex , secondIndex ) is same as ( i , j ) ; check if ( firstIndex , secondIndex ) is a valid point ; Driver Code ; equation of line is y = mx + c | #include <bits/stdc++.h> NEW_LINE using namespace std ; bool isValid ( int arr [ ] , int i , int j , int m , int c ) { if ( i == j ) return false ; int lhs = arr [ j ] ; int rhs = m * arr [ i ] + c ; return ( lhs == rhs ) ; } int findOrderedPoints ( int arr [ ] , int n , int m , int c ) { int counter = 0 ; for ( int i = 0 ; i < n ; i ++ ) { for ( int j = 0 ; j < n ; j ++ ) { int firstIndex = i , secondIndex = j ; if ( isValid ( arr , firstIndex , secondIndex , m , c ) ) counter ++ ; } } return counter ; } int main ( ) { int arr [ ] = { 1 , 2 , 3 , 4 , 2 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; int m = 1 , c = 1 ; cout << findOrderedPoints ( arr , n , m , c ) ; return 0 ; } |
Check if a given circle lies completely inside the ring formed by two concentric circles | CPP code to check if a circle lies in the ring ; Function to check if circle lies in the ring ; distance between center of circle center of concentric circles ( origin ) using Pythagoras theorem ; Condition to check if circle is strictly inside the ring ; Driver Code ; Both circle with radius ' r ' and ' R ' have center ( 0 , 0 ) | #include <bits/stdc++.h> NEW_LINE using namespace std ; bool checkcircle ( int r , int R , int r1 , int x1 , int y1 ) { int dis = sqrt ( x1 * x1 + y1 * y1 ) ; return ( dis - r1 >= R && dis + r1 <= r ) ; } int main ( ) { int r = 8 , R = 4 , r1 = 2 , x1 = 6 , y1 = 0 ; if ( checkcircle ( r , R , r1 , x1 , y1 ) ) cout << " yes " << endl ; else cout << " no " << endl ; return 0 ; } |
Program for Surface Area of Octahedron | CPP Program to calculate surface area of Octahedron ; utility Function ; Driver Function | #include <bits/stdc++.h> NEW_LINE using namespace std ; double surface_area_octahedron ( double side ) { return ( 2 * ( sqrt ( 3 ) ) * ( side * side ) ) ; } int main ( ) { double side = 7 ; cout << " Surface β area β of β octahedron β = " << surface_area_octahedron ( side ) << endl ; } |
Count of different straight lines with total n points with m collinear | CPP program to count number of straight lines with n total points , out of which m are collinear . ; Returns value of binomial coefficient Code taken from https : goo . gl / vhy4jp ; C [ 0 ] = 1 ; nC0 is 1 ; Compute next row of pascal triangle using the previous row ; function to calculate number of straight lines can be formed ; driver function | #include <bits/stdc++.h> NEW_LINE using namespace std ; int nCk ( int n , int k ) { int C [ k + 1 ] ; memset ( C , 0 , sizeof ( C ) ) ; for ( int i = 1 ; i <= n ; i ++ ) { for ( int j = min ( i , k ) ; j > 0 ; j -- ) C [ j ] = C [ j ] + C [ j - 1 ] ; } return C [ k ] ; } int count_Straightlines ( int n , int m ) { return ( nCk ( n , 2 ) - nCk ( m , 2 ) + 1 ) ; } int main ( ) { int n = 4 , m = 3 ; cout << count_Straightlines ( n , m ) ; return 0 ; } |
Calculate Volume of Dodecahedron | CPP program to calculate Volume of dodecahedron ; utility Function ; Driver Function | #include <bits/stdc++.h> NEW_LINE using namespace std ; double vol_of_dodecahedron ( int side ) { return ( ( ( 15 + ( 7 * ( sqrt ( 5 ) ) ) ) / 4 ) * ( pow ( side , 3 ) ) ) ; } int main ( ) { int side = 4 ; cout << " Volume β of β dodecahedron β = β " << vol_of_dodecahedron ( side ) ; } |
Program to check if water tank overflows when n solid balls are dipped in the water tank | C ++ Program to check if water tank overflows when n solid balls are dipped in the water tank ; function to find if tak will overflow or not ; cylinder capacity ; volume of water in tank ; volume of n balls ; total volume of water and n dipped balls ; condition to check if tank is in overflow state or not ; main function ; giving dimensions ; calling function | #include <bits/stdc++.h> NEW_LINE using namespace std ; void overflow ( int H , int r , int h , int N , int R ) { float tank_cap = 3.14 * r * r * H ; float water_vol = 3.14 * r * r * h ; float balls_vol = N * ( 4 / 3 ) * 3.14 * R * R * R ; float vol = water_vol + balls_vol ; if ( vol > tank_cap ) { cout << " Overflow " << endl ; } else { cout << " Not β in β overflow β state " << endl ; } } int main ( ) { int H = 10 , r = 5 , h = 5 , N = 2 , R = 2 ; overflow ( H , r , h , N , R ) ; return 0 ; } |
Program to check if tank will overflow , underflow or filled in given time | C ++ program to check if Tank will overflow or not in given time ; function to calculate the volume of tank ; function to print overflow / filled / underflow accordingly ; driver function ; radius of the tank ; height of the tank ; rate of flow of water ; time given ; calculate the required time ; printing the result | #include <bits/stdc++.h> NEW_LINE using namespace std ; float volume ( int radius , int height ) { return ( ( 22 / 7 ) * radius * radius * height ) ; } void check_and_print ( float required_time , float given_time ) { if ( required_time < given_time ) cout << " Overflow " ; else if ( required_time > given_time ) cout << " Underflow " ; else cout << " Filled " ; } int main ( ) { int radius = 5 , height = 10 , rate_of_flow = 10 ; float given_time = 70.0 ; float required_time = volume ( radius , height ) / rate_of_flow ; check_and_print ( required_time , given_time ) ; return 0 ; } |
Program to find third side of triangle using law of cosines | CPP program to find third side of triangle using law of cosines ; Function to calculate cos value of angle c ; Converting degrees to radian ; Maps the sum along the series ; Holds the actual value of sin ( n ) ; Function to find third side ; Driver program to check the above function ; function call | #include <bits/stdc++.h> NEW_LINE using namespace std ; float cal_cos ( float n ) { float accuracy = 0.0001 , x1 , denominator , cosx , cosval ; n = n * ( 3.142 / 180.0 ) ; x1 = 1 ; cosx = x1 ; cosval = cos ( n ) ; int i = 1 ; do { denominator = 2 * i * ( 2 * i - 1 ) ; x1 = - x1 * n * n / denominator ; cosx = cosx + x1 ; i = i + 1 ; } while ( accuracy <= fabs ( cosval - cosx ) ) ; return cosx ; } float third_side ( int a , int b , float c ) { float angle = cal_cos ( c ) ; return sqrt ( ( a * a ) + ( b * b ) - 2 * a * b * angle ) ; } int main ( ) { float c = 49 ; int a = 5 , b = 8 ; cout << third_side ( a , b , c ) ; return 0 ; } |
Check whether given circle resides in boundary maintained by two other circles | CPP program to check whether circle with given co - ordinates reside within the boundary of outer circle and inner circle ; function to check if given circle fit in boundary or not ; Distance from the center ; Checking the corners of circle ; driver program ; Radius of outer circle and inner circle respectively ; Co - ordinates and radius of the circle to be checked | #include <bits/stdc++.h> NEW_LINE using namespace std ; void fitOrNotFit ( int R , int r , int x , int y , int rad ) { double val = sqrt ( pow ( x , 2 ) + pow ( y , 2 ) ) ; if ( val + rad <= R && val - rad >= R - r ) cout << " Fits STRNEWLINE " ; else cout << " Doesn ' t β Fit STRNEWLINE " ; } int main ( ) { int R = 8 , r = 4 ; int x = 5 , y = 3 , rad = 3 ; fitOrNotFit ( R , r , x , y , rad ) ; return 0 ; } |
Number of Triangles that can be formed given a set of lines in Euclidean Plane | C ++ program to find the number of triangles that can be formed using a set of lines in Euclidean Plane ; double variables can ' t β be β checked β precisely β using β ' == ' this function returns true if the double variables are equal ; This function returns the number of triangles for a given set of lines ; slope array stores the slope of lines ; slope array is sorted so that all lines with same slope come together ; After sorting slopes , count different slopes . k is index in count [ ] . ; int this_count = 1 ; Count of current slope ; calculating sum1 ( Sum of all slopes ) sum1 = m1 + m2 + ... ; calculating sum2 . sum2 = m1 * m2 + m2 * m3 + ... ; int temp [ n ] ; Needed for sum3 ; calculating sum3 which gives the final answer m1 * m2 * m3 + m2 * m3 * m4 + ... ; Driver code ; lines are stored as arrays of a , b and c for ' ax + by = c ' ; n is the number of lines | #include <bits/stdc++.h> NEW_LINE using namespace std ; #define EPSILON numeric_limits<double>::epsilon() NEW_LINE bool compareDoubles ( double A , double B ) { double diff = A - B ; return ( diff < EPSILON ) && ( - diff < EPSILON ) ; } int numberOfTringles ( int a [ ] , int b [ ] , int c [ ] , int n ) { double slope [ n ] ; for ( int i = 0 ; i < n ; i ++ ) slope [ i ] = ( a [ i ] * 1.0 ) / b [ i ] ; sort ( slope , slope + n ) ; int count [ n ] , k = 0 ; for ( int i = 1 ; i < n ; i ++ ) { if ( compareDoubles ( slope [ i ] , slope [ i - 1 ] ) ) this_count ++ ; else { count [ k ++ ] = this_count ; this_count = 1 ; } } count [ k ++ ] = this_count ; int sum1 = 0 ; for ( int i = 0 ; i < k ; i ++ ) sum1 += count [ i ] ; int sum2 = 0 ; for ( int i = 0 ; i < k ; i ++ ) { temp [ i ] = count [ i ] * ( sum1 - count [ i ] ) ; sum2 += temp [ i ] ; } sum2 /= 2 ; int sum3 = 0 ; for ( int i = 0 ; i < k ; i ++ ) sum3 += count [ i ] * ( sum2 - temp [ i ] ) ; sum3 /= 3 ; return sum3 ; } int main ( ) { int a [ ] = { 1 , 2 , 3 , 4 } ; int b [ ] = { 2 , 4 , 5 , 5 } ; int c [ ] = { 5 , 7 , 8 , 6 } ; int n = sizeof ( a ) / sizeof ( a [ 0 ] ) ; cout << " The β number β of β triangles β that " " β can β be β formed β are : β " << numberOfTringles ( a , b , c , n ) ; return 0 ; } |
Program to find line passing through 2 Points | C ++ Implementation to find the line passing through two points ; This pair is used to store the X and Y coordinate of a point respectively ; Function to find the line given two points ; Driver code | #include <iostream> NEW_LINE using namespace std ; #define pdd pair<double, double> NEW_LINE void lineFromPoints ( pdd P , pdd Q ) { double a = Q . second - P . second ; double b = P . first - Q . first ; double c = a * ( P . first ) + b * ( P . second ) ; if ( b < 0 ) { cout << " The β line β passing β through β points β P β and β Q β " " is : β " << a << " x β - β " << b << " y β = β " << c << endl ; } else { cout << " The β line β passing β through β points β P β and β Q β " " is : β " << a << " x β + β " << b << " y β = β " << c << endl ; } } int main ( ) { pdd P = make_pair ( 3 , 2 ) ; pdd Q = make_pair ( 2 , 6 ) ; lineFromPoints ( P , Q ) ; return 0 ; } |
Regular polygon using only 1 s in a binary numbered circle | C ++ program to find whether a regular polygon is possible in circle with 1 s as vertices ; method returns true if polygon is possible with ' midpoints ' number of midpoints ; loop for getting first vertex of polygon ; loop over array values at ' midpoints ' distance ; and ( & ) all those values , if even one of them is 0 , val will be 0 ; if val is still 1 and ( N / midpoints ) or ( number of vertices ) are more than two ( for a polygon minimum ) print result and return true ; method prints sides in the polygon or print not possible in case of no possible polygon ; limit for iterating over divisors ; If i divides N then i and ( N / i ) will be divisors ; check polygon for both divisors ; Driver code to test above methods | #include <bits/stdc++.h> NEW_LINE using namespace std ; bool checkPolygonWithMidpoints ( int arr [ ] , int N , int midpoints ) { for ( int j = 0 ; j < midpoints ; j ++ ) { int val = 1 ; for ( int k = j ; k < N ; k += midpoints ) { val &= arr [ k ] ; } if ( val && N / midpoints > 2 ) { cout << " Polygon β possible β with β side β length β " << << ( N / midpoints ) << endl ; return true ; } } return false ; } void isPolygonPossible ( int arr [ ] , int N ) { int limit = sqrt ( N ) ; for ( int i = 1 ; i <= limit ; i ++ ) { if ( N % i == 0 ) { if ( checkPolygonWithMidpoints ( arr , N , i ) || checkPolygonWithMidpoints ( arr , N , ( N / i ) ) ) return ; } } cout << " Not β possiblen " ; } int main ( ) { int arr [ ] = { 1 , 0 , 1 , 0 , 1 , 0 , 1 , 0 , 1 , 1 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; isPolygonPossible ( arr , N ) ; return 0 ; } |
Minimum lines to cover all points | C ++ program to get minimum lines to cover all the points ; Utility method to get gcd of a and b ; method returns reduced form of dy / dx as a pair ; get sign of result ; method returns minimum number of lines to cover all points where all lines goes through ( xO , yO ) ; set to store slope as a pair ; loop over all points once ; get x and y co - ordinate of current point ; if this slope is not there in set , increase ans by 1 and insert in set ; Driver code to test above methods | #include <bits/stdc++.h> NEW_LINE using namespace std ; int gcd ( int a , int b ) { if ( b == 0 ) return a ; return gcd ( b , a % b ) ; } pair < int , int > getReducedForm ( int dy , int dx ) { int g = gcd ( abs ( dy ) , abs ( dx ) ) ; bool sign = ( dy < 0 ) ^ ( dx < 0 ) ; if ( sign ) return make_pair ( - abs ( dy ) / g , abs ( dx ) / g ) ; else return make_pair ( abs ( dy ) / g , abs ( dx ) / g ) ; } int minLinesToCoverPoints ( int points [ ] [ 2 ] , int N , int xO , int yO ) { set < pair < int , int > > st ; pair < int , int > temp ; int minLines = 0 ; for ( int i = 0 ; i < N ; i ++ ) { int curX = points [ i ] [ 0 ] ; int curY = points [ i ] [ 1 ] ; temp = getReducedForm ( curY - yO , curX - xO ) ; if ( st . find ( temp ) == st . end ( ) ) { st . insert ( temp ) ; minLines ++ ; } } return minLines ; } int main ( ) { int xO , yO ; xO = 1 ; yO = 0 ; int points [ ] [ 2 ] = { { -1 , 3 } , { 4 , 3 } , { 2 , 1 } , { -1 , -2 } , { 3 , -3 } } ; int N = sizeof ( points ) / sizeof ( points [ 0 ] ) ; cout << minLinesToCoverPoints ( points , N , xO , yO ) ; return 0 ; } |
Maximum height when coins are arranged in a triangle | C ++ program to find maximum height of arranged coin triangle ; Returns the square root of n . Note that the function ; We are using n itself as initial approximation This can definitely be improved ; e decides the accuracy level ; Method to find maximum height of arrangement of coins ; calculating portion inside the square root ; Driver code to test above method | #include <bits/stdc++.h> NEW_LINE using namespace std ; float squareRoot ( float n ) { float x = n ; float y = 1 ; float e = 0.000001 ; while ( x - y > e ) { x = ( x + y ) / 2 ; y = n / x ; } return x ; } int findMaximumHeight ( int N ) { int n = 1 + 8 * N ; int maxH = ( -1 + squareRoot ( n ) ) / 2 ; return maxH ; } int main ( ) { int N = 12 ; cout << findMaximumHeight ( N ) << endl ; return 0 ; } |
Number of Integral Points between Two Points | C ++ code to find the number of integral points lying on the line joining the two given points ; Class to represent an Integral point on XY plane . ; Utility function to find GCD of two numbers GCD of a and b ; Finds the no . of Integral points between two given points . ; If line joining p and q is parallel to x axis , then count is difference of y values ; If line joining p and q is parallel to y axis , then count is difference of x values ; Driver program to test above | #include <iostream> NEW_LINE #include <cmath> NEW_LINE using namespace std ; class Point { public : int x , y ; Point ( int a = 0 , int b = 0 ) : x ( a ) , y ( b ) { } } ; int gcd ( int a , int b ) { if ( b == 0 ) return a ; return gcd ( b , a % b ) ; } int getCount ( Point p , Point q ) { if ( p . x == q . x ) return abs ( p . y - q . y ) - 1 ; if ( p . y == q . y ) return abs ( p . x - q . x ) - 1 ; return gcd ( abs ( p . x - q . x ) , abs ( p . y - q . y ) ) - 1 ; } int main ( ) { Point p ( 1 , 9 ) ; Point q ( 8 , 16 ) ; cout << " The β number β of β integral β points β between β " << " ( " << p . x << " , β " << p . y << " ) β and β ( " << q . x << " , β " << q . y << " ) β is β " << getCount ( p , q ) ; return 0 ; } |
How to check if given four points form a square | A C ++ program to check if four given points form a square or not . ; Structure of a point in 2D space ; A utility function to find square of distance from point ' p ' to point ' q ' ; This function returns true if ( p1 , p2 , p3 , p4 ) form a square , otherwise false ; int d2 = distSq ( p1 , p2 ) ; from p1 to p2 int d3 = distSq ( p1 , p3 ) ; from p1 to p3 int d4 = distSq ( p1 , p4 ) ; from p1 to p4 ; If lengths if ( p1 , p2 ) and ( p1 , p3 ) are same , then following conditions must met to form a square . 1 ) Square of length of ( p1 , p4 ) is same as twice the square of ( p1 , p2 ) 2 ) Square of length of ( p2 , p3 ) is same as twice the square of ( p2 , p4 ) ; The below two cases are similar to above case ; Driver program to test above function | #include <iostream> NEW_LINE using namespace std ; struct Point { int x , y ; } ; int distSq ( Point p , Point q ) { return ( p . x - q . x ) * ( p . x - q . x ) + ( p . y - q . y ) * ( p . y - q . y ) ; } bool isSquare ( Point p1 , Point p2 , Point p3 , Point p4 ) { if ( d2 == 0 d3 == 0 d4 == 0 ) return false ; if ( d2 == d3 && 2 * d2 == d4 && 2 * distSq ( p2 , p4 ) == distSq ( p2 , p3 ) ) { return true ; } if ( d3 == d4 && 2 * d3 == d2 && 2 * distSq ( p3 , p2 ) == distSq ( p3 , p4 ) ) { return true ; } if ( d2 == d4 && 2 * d2 == d3 && 2 * distSq ( p2 , p3 ) == distSq ( p2 , p4 ) ) { return true ; } return false ; } int main ( ) { Point p1 = { 20 , 10 } , p2 = { 10 , 20 } , p3 = { 20 , 20 } , p4 = { 10 , 10 } ; isSquare ( p1 , p2 , p3 , p4 ) ? cout << " Yes " : cout << " No " ; return 0 ; } |
Count triplets such that product of two numbers added with third number is N | C ++ program for the above approach ; Function to find the divisors of the number ( N - i ) ; Stores the resultant count of divisors of ( N - i ) ; Iterate over range [ 1 , sqrt ( N ) ] ; Return the total divisors ; Function to find the number of triplets such that A * B - C = N ; Loop to fix the value of C ; Adding the number of divisors in count ; Return count of triplets ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int countDivisors ( int n ) { int divisors = 0 ; int i ; for ( i = 1 ; i * i < n ; i ++ ) { if ( n % i == 0 ) { divisors ++ ; } } if ( i - ( n / i ) == 1 ) { i -- ; } for ( ; i >= 1 ; i -- ) { if ( n % i == 0 ) { divisors ++ ; } } return divisors ; } int possibleTriplets ( int N ) { int count = 0 ; for ( int i = 1 ; i < N ; i ++ ) { count += countDivisors ( N - i ) ; } return count ; } int main ( ) { int N = 10 ; cout << possibleTriplets ( N ) ; return 0 ; } |
Maximize count of planes that can be stopped per second with help of given initial position and speed | C ++ program for the above approach ; Function to find maximum number of planes that can be stopped from landing ; Stores the times needed for landing for each plane ; Iterate over the arrays ; Stores the time needed for landing of current plane ; Update the value of t ; Append the t in set St ; Return the answer ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int maxPlanes ( int A [ ] , int B [ ] , int N ) { set < int > St ; for ( int i = 0 ; i < N ; i ++ ) { int t = ( A [ i ] % B [ i ] > 0 ) ? 1 : 0 ; t += ( A [ i ] / B [ i ] ) + t ; St . insert ( t ) ; } return St . size ( ) ; } int main ( ) { int A [ ] = { 1 , 3 , 5 , 4 , 8 } ; int B [ ] = { 1 , 2 , 2 , 1 , 2 } ; int N = sizeof ( A ) / sizeof ( A [ 0 ] ) ; cout << maxPlanes ( A , B , N ) ; return 0 ; } |
Find the player who will win by choosing a number in range [ 1 , K ] with sum total N | C ++ program for above approach ; Function to predict the winner ; Driver Code ; Given Input ; Function call | #include <iostream> NEW_LINE using namespace std ; void predictTheWinner ( int K , int N ) { if ( N % ( K + 1 ) == 0 ) cout << " Bob " ; else cout << " Alice " ; } int main ( ) { int K = 7 , N = 50 ; predictTheWinner ( K , N ) ; return 0 ; } |
Maximize the rightmost element of an array in k operations in Linear Time | C ++ program for above approach ; Function to calculate maximum value of Rightmost element ; Initializing ans to store Maximum valued rightmost element ; Calculating maximum value of Rightmost element ; Printing rightmost element ; Driver Code ; Given Input ; Function Call | #include <iostream> NEW_LINE using namespace std ; void maxRightmostElement ( int N , int k , int arr [ ] ) { int ans = arr [ N - 1 ] ; for ( int i = N - 2 ; i >= 0 ; i -- ) { int d = min ( arr [ i ] / 2 , k / ( N - 1 - i ) ) ; k -= d * ( N - 1 - i ) ; ans += d * 2 ; } cout << ans << endl ; } int main ( ) { int N = 4 , k = 5 , arr [ ] = { 3 , 8 , 1 , 4 } ; maxRightmostElement ( N , k , arr ) ; return 0 ; } |
Minimize the maximum element in constructed Array with sum divisible by K | C ++ program for the above approach . ; Function to find smallest maximum number in an array whose sum is divisible by K . ; Minimum possible sum possible for an array of size N such that its sum is divisible by K ; If sum is not divisible by N ; If sum is divisible by N ; Driver code . | #include <iostream> NEW_LINE using namespace std ; int smallestMaximum ( int N , int K ) { int sum = ( ( N + K - 1 ) / K ) * K ; if ( sum % N != 0 ) return ( sum / N ) + 1 ; else return sum / N ; } int main ( ) { int N = 4 ; int K = 3 ; cout << smallestMaximum ( N , K ) << endl ; return 0 ; } |
Check if it is possible to construct an Array of size N having sum as S and XOR value as X | C ++ program for the above approach ; Function to find if any sequence is possible or not . ; Since , S is greater than equal to X , and either both are odd or even There always exists a sequence ; Only one case possible is S == X or NOT ; ; Considering the above conditions true , check if XOR of S ^ ( S - X ) is X or not ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; string findIfPossible ( int N , int S , int X ) { if ( S >= X and S % 2 == X % 2 ) { if ( N >= 3 ) { return " Yes " ; } if ( N == 1 ) { if ( S == X ) { return " Yes " ; } else { return " No " ; } } if ( N == 2 ) { int C = ( S - X ) / 2 ; int A = C ; int B = C ; A = A + X ; if ( ( ( A ^ B ) == X ) ) { return " Yes " ; } else { return " No " ; } } } else { return " No " ; } } int main ( ) { int N = 3 , S = 10 , X = 4 ; cout << findIfPossible ( N , S , X ) ; return 0 ; } |
Check whether each Array element can be reduced to minimum element by replacing it with remainder with some X | C ++ program for the above approach ; Function to check if every integer in the array can be reduced to the minimum array element ; Stores the minimum array element ; Find the minimum element ; Traverse the array arr [ ] ; Stores the maximum value in the range ; Check whether mini lies in the range or not ; Otherwise , return Yes ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; string isPossible ( int arr [ ] , int n ) { int mini = INT_MAX ; for ( int i = 0 ; i < n ; i ++ ) mini = min ( mini , arr [ i ] ) ; for ( int i = 0 ; i < n ; i ++ ) { if ( arr [ i ] == mini ) continue ; int Max = ( arr [ i ] + 1 ) / 2 - 1 ; if ( mini < 0 mini > Max ) return " No " ; } return " Yes " ; } int main ( ) { int arr [ ] = { 1 , 1 , 3 , 4 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << isPossible ( arr , N ) ; return 0 ; } |
Maximum number which can divide all array element after one replacement | C ++ Implementation for the above approach ; Function to return gcd of two numbers ; If one of numbers is 0 then gcd is other number ; If both are equal then that value is gcd ; One is greater ; Function to return minimum sum ; Initialize min_sum with large value ; Initialize variable gcd ; Storing value of arr [ i ] in c ; Update maxGcd if gcd is greater than maxGcd ; returning the maximum divisor of all elements ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int gcdOfTwoNos ( int num1 , int num2 ) { if ( num1 == 0 ) return num2 ; if ( num2 == 0 ) return num1 ; if ( num1 == num2 ) return num1 ; if ( num1 > num2 ) return gcdOfTwoNos ( num1 - num2 , num2 ) ; return gcdOfTwoNos ( num1 , num2 - num1 ) ; } int Min_sum ( int arr [ ] , int N ) { int min_sum = 1000000 , maxGcd = 1 ; for ( int i = 0 ; i < N ; i ++ ) { int gcd ; if ( i == 0 ) gcd = arr [ 1 ] ; else { gcd = arr [ i - 1 ] ; } for ( int j = 0 ; j < N ; j ++ ) { if ( j != i ) gcd = gcdOfTwoNos ( gcd , arr [ j ] ) ; } int c = arr [ i ] ; if ( gcd > maxGcd ) maxGcd = gcd ; } return maxGcd ; } int main ( ) { int arr [ ] = { 16 , 5 , 10 , 25 } ; int N = sizeof ( arr ) / sizeof ( int ) ; cout << Min_sum ( arr , N ) ; return 0 ; } |
Count of distinct N | C ++ Program for the above approach ; Function to find the count of distinct odd integers with N digits using the given digits in the array arr [ ] ; Stores the factorial of a number ; Calculate the factorial of all numbers from 1 to N ; Stores the frequency of each digit ; Stores the final answer ; Loop to iterate over all values of Nth digit i and 1 st digit j ; If digit i does not exist in the given array move to next i ; Fixing i as Nth digit ; Stores the answer of a specific value of i and j ; If digit j does not exist move to the next j ; Fixing j as 1 st digit ; Calculate number of ways to arrange remaining N - 2 digits ; Including j back into the set of digits ; Including i back into the set of the digits ; Return Answer ; Driver Code ; Function Call | #include <bits/stdc++.h> NEW_LINE using namespace std ; int countOddIntegers ( int arr [ ] , int N ) { int Fact [ N ] = { } ; Fact [ 0 ] = 1 ; for ( int i = 1 ; i < N ; i ++ ) { Fact [ i ] = i * Fact [ i - 1 ] ; } int freq [ 10 ] = { } ; for ( int i = 0 ; i < N ; i ++ ) { freq [ arr [ i ] ] ++ ; } int ans = 0 ; for ( int i = 1 ; i <= 9 ; i += 2 ) { if ( ! freq [ i ] ) continue ; freq [ i ] -- ; for ( int j = 1 ; j <= 9 ; j ++ ) { int cur_ans = 0 ; if ( freq [ j ] == 0 ) { continue ; } freq [ j ] -- ; cur_ans = Fact [ N - 2 ] ; for ( int k = 0 ; k <= 9 ; k ++ ) { cur_ans = cur_ans / Fact [ freq [ k ] ] ; } ans += cur_ans ; freq [ j ] ++ ; } freq [ i ] ++ ; } return ans ; } int main ( ) { int A [ ] = { 2 , 3 , 4 , 1 , 2 , 3 } ; int N = sizeof ( A ) / sizeof ( int ) ; cout << countOddIntegers ( A , N ) ; return 0 ; } |
Count pairs in an array having sum of elements with their respective sum of digits equal | C ++ program for the above approach ; Function to find the sum of digits of the number N ; Stores the sum of digits ; If the number N is greater than 0 ; Return the sum ; Function to find the count of pairs such that arr [ i ] + sumOfDigits ( arr [ i ] ) is equal to ( arr [ j ] + sumOfDigits ( arr [ j ] ) ; Stores the frequency of value of arr [ i ] + sumOfDigits ( arr [ i ] ) ; Traverse the given array ; Find the value ; Increment the frequency ; Stores the total count of pairs ; Traverse the map mp ; Update the count of pairs ; Return the total count of pairs ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int sumOfDigits ( int N ) { int sum = 0 ; while ( N ) { sum += ( N % 10 ) ; N = N / 10 ; } return sum ; } int CountPair ( int arr [ ] , int n ) { unordered_map < int , int > mp ; for ( int i = 0 ; i < n ; i ++ ) { int val = arr [ i ] + sumOfDigits ( arr [ i ] ) ; mp [ val ] ++ ; } int count = 0 ; for ( auto x : mp ) { int val = x . first ; int times = x . second ; count += ( ( times * ( times - 1 ) ) / 2 ) ; } return count ; } int main ( ) { int arr [ ] = { 105 , 96 , 20 , 2 , 87 , 96 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << CountPair ( arr , N ) ; return 0 ; } |
Longest subarray with GCD greater than 1 | C ++ program of the above approach ; Function to build the Segment Tree from the given array to process range queries in log ( N ) time ; Termination Condition ; Find the mid value ; Left and Right Recursive Call ; Update the Segment Tree Node ; Function to return the GCD of the elements of the Array from index l to index r ; Base Case ; Find the middle range ; Find the GCD and return ; Function to print maximum length of the subarray having GCD > one ; Stores the Segment Tree ; Function call to build the Segment tree from array arr [ ] ; Store maximum length of subarray ; Starting and ending pointer of the current window ; Case where the GCD of the current window is 1 ; Update the maximum length ; Print answer ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; void build_tree ( int * b , vector < int > & seg_tree , int l , int r , int vertex ) { if ( l == r ) { seg_tree [ vertex ] = b [ l ] ; return ; } int mid = ( l + r ) / 2 ; build_tree ( b , seg_tree , l , mid , 2 * vertex ) ; build_tree ( b , seg_tree , mid + 1 , r , 2 * vertex + 1 ) ; seg_tree [ vertex ] = __gcd ( seg_tree [ 2 * vertex ] , seg_tree [ 2 * vertex + 1 ] ) ; } int range_gcd ( vector < int > & seg_tree , int v , int tl , int tr , int l , int r ) { if ( l > r ) return 0 ; if ( l == tl && r == tr ) return seg_tree [ v ] ; int tm = ( tl + tr ) / 2 ; return __gcd ( range_gcd ( seg_tree , 2 * v , tl , tm , l , min ( tm , r ) ) , range_gcd ( seg_tree , 2 * v + 1 , tm + 1 , tr , max ( tm + 1 , l ) , r ) ) ; } void maxSubarrayLen ( int arr [ ] , int n ) { vector < int > seg_tree ( 4 * ( n ) + 1 , 0 ) ; build_tree ( arr , seg_tree , 0 , n - 1 , 1 ) ; int maxLen = 0 ; int l = 0 , r = 0 ; while ( r < n && l < n ) { if ( range_gcd ( seg_tree , 1 , 0 , n - 1 , l , r ) == 1 ) { l ++ ; } maxLen = max ( maxLen , r - l + 1 ) ; r ++ ; } cout << maxLen ; } int main ( ) { int arr [ ] = { 410 , 52 , 51 , 180 , 222 , 33 , 33 } ; int N = sizeof ( arr ) / sizeof ( int ) ; maxSubarrayLen ( arr , N ) ; return 0 ; } |
Smallest pair of integers with minimum difference whose Bitwise XOR is N | C ++ program for the above approach ; Function to find the numbers A and B whose Bitwise XOR is N and the difference between them is minimum ; Find the MSB of the N ; Find the value of B ; Find the value of A ; Print the result ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; void findAandB ( int N ) { int K = log2 ( N ) ; int B = ( 1 << K ) ; int A = B ^ N ; cout << A << ' β ' << B ; } int main ( ) { int N = 26 ; findAandB ( N ) ; return 0 ; } |
Find all possible values of K such that the sum of first N numbers starting from K is G | C ++ program for the above approach ; Function to find the count the value of K such that sum of the first N numbers from K is G ; Stores the total count of K ; Iterate till square root of g ; If the number is factor of g ; If the second factor is not equal to first factor ; Check if two factors are odd or not ; If second factor is the same as the first factor then check if the first factor is odd or not ; Print the resultant count ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; void findValuesOfK ( int g ) { int count = 0 ; for ( int i = 1 ; i * i <= g ; i ++ ) { if ( g % i == 0 ) { if ( i != g / i ) { if ( i & 1 ) { count ++ ; } if ( ( g / i ) & 1 ) { count ++ ; } } else if ( i & 1 ) { count ++ ; } } } cout << count ; } int main ( ) { int G = 125 ; findValuesOfK ( G ) ; return 0 ; } |
Difference between maximum and minimum average of all K | C ++ program for the above approach ; Function to find the difference between the maximum and minimum subarrays of length K ; Stores the sum of subarray over the range [ 0 , K ] ; Iterate over the range [ 0 , K ] ; Store min and max sum ; Iterate over the range [ K , N - K ] ; Increment sum by arr [ i ] - arr [ i - K ] ; Update max and min moving sum ; Return difference between max and min average ; Driver Code ; Given Input ; Function Call | #include <bits/stdc++.h> NEW_LINE using namespace std ; double Avgdifference ( double arr [ ] , int N , int K ) { double sum = 0 ; for ( int i = 0 ; i < K ; i ++ ) sum += arr [ i ] ; double min = sum ; double max = sum ; for ( int i = K ; i <= N - K + 1 ; i ++ ) { sum += arr [ i ] - arr [ i - K ] ; if ( min > sum ) min = sum ; if ( max < sum ) max = sum ; } return ( max - min ) / K ; } int main ( ) { double arr [ ] = { 3 , 8 , 9 , 15 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; int K = 2 ; cout << Avgdifference ( arr , N , K ) ; return 0 ; } |
Count of distinct integers in range [ 1 , N ] that do not have any subset sum as K | C ++ program for the above approach ; Function to find maximum number of distinct integers in [ 1 , N ] having no subset with sum equal to K ; Declare a vector to store the required numbers ; Store all the numbers in [ 1 , N ] except K ; Store the maximum number of distinct numbers ; Reverse the array ; Print the required numbers ; Driver Code ; Given Input ; Function Call | #include <bits/stdc++.h> NEW_LINE using namespace std ; void findSet ( int N , int K ) { vector < int > a ; for ( int i = 1 ; i <= N ; i ++ ) { if ( i != K ) a . push_back ( i ) ; } int MaxDistinct = ( N - K ) + ( K / 2 ) ; reverse ( a . begin ( ) , a . end ( ) ) ; for ( int i = 0 ; i < MaxDistinct ; i ++ ) cout << a [ i ] << " β " ; } int main ( ) { int N = 5 , K = 3 ; findSet ( N , K ) ; return 0 ; } |
Solve Linear Congruences Ax = B ( mod N ) for values of x in range [ 0 , N | C ++ program for the above approach ; Function to stores the values of x and y and find the value of gcd ( a , b ) ; Base Case ; Store the result of recursive call ; Update x and y using results of recursive call ; Function to give the distinct solutions of ax = b ( mod n ) ; Function Call to find the value of d and u ; No solution exists ; Else , initialize the value of x0 ; Print all the answers ; Driver Code ; Input ; Function Call | #include <bits/stdc++.h> NEW_LINE using namespace std ; long long ExtendedEuclidAlgo ( long long a , long long b , long long & x , long long & y ) { if ( b == 0 ) { x = 1 ; y = 0 ; return a ; } else { long long x1 , y1 ; long long gcd = ExtendedEuclidAlgo ( b , a % b , x1 , y1 ) ; x = y1 ; y = x1 - floor ( a / b ) * y1 ; return gcd ; } } void linearCongruence ( long long A , long long B , long long N ) { A = A % N ; B = B % N ; long long u = 0 , v = 0 ; long long d = ExtendedEuclidAlgo ( A , N , u , v ) ; if ( B % d != 0 ) { cout << -1 << endl ; return ; } long long x0 = ( u * ( B / d ) ) % N ; if ( x0 < 0 ) x0 += N ; for ( long long i = 0 ; i <= d - 1 ; i ++ ) cout << ( x0 + i * ( N / d ) ) % N << " β " ; } int main ( ) { long long A = 15 ; long long B = 9 ; long long N = 18 ; linearCongruence ( A , B , N ) ; return 0 ; } |
Factorial of a number without using multiplication | C ++ program for the above approach ; Function to calculate factorial of the number without using multiplication operator ; variable to store the final factorial ; Outer loop ; Inner loop ; Driver code ; Input ; Function calling | #include <bits/stdc++.h> NEW_LINE using namespace std ; int factorialWithoutMul ( int N ) { int ans = N ; for ( int i = N - 1 ; i > 0 ; i -- ) { int sum = 0 ; for ( int j = 0 ; j < i ; j ++ ) sum += ans ; ans = sum ; } return ans ; } int main ( ) { int N = 5 ; cout << factorialWithoutMul ( N ) << endl ; return 0 ; } |
Sum of Bitwise AND of all unordered triplets of an array | C ++ program for the above approach ; Function to calculate sum of Bitwise AND of all unordered triplets from a given array such that ( i < j < k ) ; Stores the resultant sum of Bitwise AND of all triplets ; Generate all triplets of ( arr [ i ] , arr [ j ] , arr [ k ] ) ; Add Bitwise AND to ans ; Print the result ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; void tripletAndSum ( int arr [ ] , int n ) { int ans = 0 ; for ( int i = 0 ; i < n ; i ++ ) { for ( int j = i + 1 ; j < n ; j ++ ) { for ( int k = j + 1 ; k < n ; k ++ ) { ans += arr [ i ] & arr [ j ] & arr [ k ] ; } } } cout << ans ; } int main ( ) { int arr [ ] = { 3 , 5 , 4 , 7 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; tripletAndSum ( arr , N ) ; return 0 ; } |
Sum of Bitwise AND of all unordered triplets of an array | C ++ program for the above approach ; Function to calculate sum of Bitwise AND of all unordered triplets from a given array such that ( i < j < k ) ; Stores the resultant sum of Bitwise AND of all triplets ; Traverse over all the bits ; Count number of elements with the current bit set ; There are ( cnt ) C ( 3 ) numbers with the current bit set and each triplet contributes 2 ^ bit to the result ; Return the resultant sum ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int tripletAndSum ( int arr [ ] , int n ) { int ans = 0 ; for ( int bit = 0 ; bit < 32 ; bit ++ ) { int cnt = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( arr [ i ] & ( 1 << bit ) ) cnt ++ ; } ans += ( 1 << bit ) * cnt * ( cnt - 1 ) * ( cnt - 2 ) / 6 ; } return ans ; } int main ( ) { int arr [ ] = { 3 , 5 , 4 , 7 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << tripletAndSum ( arr , N ) ; return 0 ; } |
Lexicographically smallest permutation of length 2 N that can be obtained from an N | C ++ program for the above approach ; Function to find the lexicographically smallest permutation of length 2 * N satisfying the given conditions ; Stores if i - th element is placed at odd position or not ; Traverse the array ; Mark arr [ i ] true ; Stores all the elements not placed at odd positions ; Iterate in the range [ 1 , 2 * N ] ; If w [ i ] is not marked ; Stores whether it is possible to obtain the required permutation or not ; Stores the permutation ; Traverse the array arr [ ] ; Finds the iterator of the smallest number greater than the arr [ i ] ; If it is S . end ( ) ; Mark found false ; Push arr [ i ] and * it into the array ; Erase the current element from the Set ; If found is not marked ; Otherwise , ; Print the permutation ; Driver Code ; Given Input ; Function call | #include <bits/stdc++.h> NEW_LINE using namespace std ; void smallestPermutation ( int arr [ ] , int N ) { vector < bool > w ( 2 * N + 1 ) ; for ( int i = 0 ; i < N ; i ++ ) { w [ arr [ i ] ] = true ; } set < int > S ; for ( int i = 1 ; i <= 2 * N ; i ++ ) { if ( ! w [ i ] ) S . insert ( i ) ; } bool found = true ; vector < int > P ; for ( int i = 0 ; i < N ; i ++ ) { auto it = S . lower_bound ( arr [ i ] ) ; if ( it == S . end ( ) ) { found = false ; break ; } P . push_back ( arr [ i ] ) ; P . push_back ( * it ) ; S . erase ( it ) ; } if ( ! found ) { cout << " - 1 STRNEWLINE " ; } else { for ( int i = 0 ; i < 2 * N ; i ++ ) cout << P [ i ] << " β " ; } } int main ( ) { int arr [ ] = { 4 , 1 , 3 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; smallestPermutation ( arr , N ) ; return 0 ; } |
Maximum sum of a subsequence having difference between their indices equal to the difference between their values | C ++ program for the above approach ; Function to find the maximum sum of a subsequence having difference between indices equal to difference in their values ; Stores the maximum sum ; Stores the value for each A [ i ] - i ; Traverse the array ; Update the value in map ; Update the answer ; Finally , print the answer ; Driver Code ; Given Input ; Function Call | #include <bits/stdc++.h> NEW_LINE using namespace std ; void maximumSubsequenceSum ( int A [ ] , int N ) { int ans = 0 ; map < int , int > mp ; for ( int i = 0 ; i < N ; i ++ ) { mp [ A [ i ] - i ] += A [ i ] ; ans = max ( ans , mp [ A [ i ] - i ] ) ; } cout << ans << endl ; } int main ( ) { int A [ ] = { 10 , 7 , 1 , 9 , 10 , 1 } ; int N = sizeof ( A ) / sizeof ( A [ 0 ] ) ; maximumSubsequenceSum ( A , N ) ; return 0 ; } |
Find the nearest perfect square for each element of the array | C ++ program for the above approach ; Function to find the nearest perfect square for every element in the given array ; Traverse the array ; Calculate square root of current element ; Calculate perfect square ; Find the nearest ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; void nearestPerfectSquare ( int arr [ ] , int N ) { for ( int i = 0 ; i < N ; i ++ ) { int sr = sqrt ( arr [ i ] ) ; int a = sr * sr ; int b = ( sr + 1 ) * ( sr + 1 ) ; if ( ( arr [ i ] - a ) < ( b - arr [ i ] ) ) cout << a << " β " ; else cout << b << " β " ; } } int main ( ) { int arr [ ] = { 5 , 2 , 7 , 13 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; nearestPerfectSquare ( arr , N ) ; return 0 ; } |
Count of sets possible using integers from a range [ 2 , N ] using given operations that are in Equivalence Relation | C ++ program for the above approach ; Sieve of Eratosthenes to find primes less than or equal to N ; Function to find number of Sets ; Handle Base Case ; Set which contains less than or equal to N / 2 ; Number greater than N / 2 and are prime increment it by 1 ; If the number is prime Increment answer by 1 ; Driver Code ; Input ; Function Call | #include <bits/stdc++.h> NEW_LINE using namespace std ; bool prime [ 100001 ] ; void SieveOfEratosthenes ( int n ) { memset ( prime , true , sizeof ( prime ) ) ; for ( int p = 2 ; p * p <= n ; p ++ ) { if ( prime [ p ] == true ) { for ( int i = p * p ; i <= n ; i += p ) prime [ i ] = false ; } } } void NumberofSets ( int N ) { SieveOfEratosthenes ( N ) ; if ( N == 2 ) { cout << 1 << endl ; } else if ( N == 3 ) { cout << 2 << endl ; } else { int ans = 1 ; for ( int i = N / 2 + 1 ; i <= N ; i ++ ) { if ( prime [ i ] ) { ans += 1 ; } } cout << ans << endl ; } } int main ( ) { int N = 9 ; NumberofSets ( N ) ; return 0 ; } |
Absolute difference between floor of Array sum divided by X and floor sum of every Array element when divided by X | C ++ program for the above approach ; Function to find absolute difference between the two sum values ; Variable to store total sum ; Variable to store sum of A [ i ] / X ; Traverse the array ; Update totalSum ; Update perElementSum ; Floor of total sum divided by X ; Return the absolute difference ; Driver Code ; Input ; Size of Array ; Function call to find absolute difference between the two sum values | #include <bits/stdc++.h> NEW_LINE using namespace std ; int floorDifference ( int A [ ] , int N , int X ) { int totalSum = 0 ; int perElementSum = 0 ; for ( int i = 0 ; i < N ; i ++ ) { totalSum += A [ i ] ; perElementSum += A [ i ] / X ; } int totalFloorSum = totalSum / X ; return abs ( totalFloorSum - perElementSum ) ; } int main ( ) { int A [ ] = { 1 , 2 , 3 , 4 , 5 , 6 } ; int X = 4 ; int N = sizeof ( A ) / sizeof ( A [ 0 ] ) ; cout << floorDifference ( A , N , X ) ; return 0 ; } |
Convert a number from base A to base B | C ++ program for the above approach ; Function to return ASCII value of a character ; Function to convert a number from given base to decimal number ; Stores the length of the string ; Initialize power of base ; Initialize result ; Decimal equivalent is str [ len - 1 ] * 1 + str [ len - 2 ] * base + str [ len - 3 ] * ( base ^ 2 ) + ... ; A digit in input number must be less than number 's base ; Update num ; Update power ; Function to return equivalent character of a given value ; Function to convert a given decimal number to a given base ; Store the result ; Repeatedly divide inputNum by base and take remainder ; Update res ; Update inputNum ; Reverse the result ; Function to convert a given number from a base to another base ; Convert the number from base A to decimal ; Convert the number from decimal to base B ; Print the result ; Driver Code ; Given input ; Function Call | #include <bits/stdc++.h> NEW_LINE using namespace std ; int val ( char c ) { if ( c >= '0' && c <= '9' ) return ( int ) c - '0' ; else return ( int ) c - ' A ' + 10 ; } int toDeci ( string str , int base ) { int len = str . size ( ) ; int power = 1 ; int num = 0 ; for ( int i = len - 1 ; i >= 0 ; i -- ) { if ( val ( str [ i ] ) >= base ) { printf ( " Invalid β Number " ) ; return -1 ; } num += val ( str [ i ] ) * power ; power = power * base ; } return num ; } char reVal ( int num ) { if ( num >= 0 && num <= 9 ) return ( char ) ( num + '0' ) ; else return ( char ) ( num - 10 + ' A ' ) ; } string fromDeci ( int base , int inputNum ) { string res = " " ; while ( inputNum > 0 ) { res += reVal ( inputNum % base ) ; inputNum /= base ; } reverse ( res . begin ( ) , res . end ( ) ) ; return res ; } void convertBase ( string s , int a , int b ) { int num = toDeci ( s , a ) ; string ans = fromDeci ( b , num ) ; cout << ans ; } int main ( ) { string s = "10B " ; int a = 16 , b = 10 ; convertBase ( s , a , b ) ; return 0 ; } |
Prefix Factorials of a Prefix Sum Array | C ++ program for the above approach ; Function to find the factorial of a number N ; Base Case ; Find the factorial recursively ; Function to find the prefix factorial array ; Find the prefix sum array ; Find the factorials of each array element ; Print the resultant array ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int fact ( int N ) { if ( N == 1 N == 0 ) return 1 ; return N * fact ( N - 1 ) ; } void prefixFactorialArray ( int arr , int N ) { for ( int i = 1 ; i < N ; i ++ ) { arr [ i ] += arr [ i - 1 ] ; } for ( int i = 0 ; i < N ; i ++ ) { arr [ i ] = fact ( arr [ i ] ) ; } for ( int i = 0 ; i < N ; i ++ ) { cout << arr [ i ] << " β " ; } } int main ( ) { int arr [ ] = { 1 , 2 , 3 , 4 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; prefixFactorialArray ( arr , N ) ; return 0 ; } |
Mean of fourth powers of first N natural numbers | C ++ program for the above approach ; Function to find the average of the fourth power of first N natural numbers ; Store the resultant average calculated using formula ; Return the average ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; double findAverage ( int N ) { double avg = ( ( 6 * N * N * N * N ) + ( 15 * N * N * N ) + ( 10 * N * N ) - 1 ) / 30.0 ; return avg ; } int main ( ) { int N = 3 ; cout << findAverage ( N ) ; return 0 ; } |
Modify array by removing ( arr [ i ] + arr [ i + 1 ] ) th element exactly K times | C ++ program for the above approach ; Function to modify array by removing every K - th element from the array ; Check if current element is the k - th element ; Stores the elements after removing every kth element ; Append the current element if it is not k - th element ; Return the new array after removing every k - th element ; Function to print the array ; Traverse the array l [ ] ; Function to print the array after performing the given operations exactly k times ; Store first N natural numbers ; Iterate over the range [ 0 , k - 1 ] ; Store sums of the two consecutive terms ; Remove every p - th element from the array ; Increment x by 1 for the next iteration ; Print the resultant array ; Driver Code ; Given arrays ; Function Call | #include <bits/stdc++.h> NEW_LINE using namespace std ; vector < int > removeEveryKth ( vector < int > l , int k ) { for ( int i = 0 ; i < l . size ( ) ; i ++ ) { if ( i % k == 0 ) l [ i ] = 0 ; } vector < int > arr ; arr . push_back ( 0 ) ; for ( int i = 1 ; i < l . size ( ) ; i ++ ) { if ( l [ i ] != 0 ) arr . push_back ( l [ i ] ) ; } return arr ; } void printArray ( vector < int > l ) { for ( int i = 1 ; i < l . size ( ) ; i ++ ) cout << l [ i ] << " β " ; cout << endl ; } void printSequence ( int n , int k ) { vector < int > l ( n + 1 ) ; for ( int i = 0 ; i < n + 1 ; i ++ ) l [ i ] = i ; int x = 1 ; for ( int i = 0 ; i < k ; i ++ ) { int p = l [ x ] + l [ x + 1 ] ; l = removeEveryKth ( l , p ) ; x += 1 ; } printArray ( l ) ; } int main ( ) { int N = 8 ; int K = 2 ; printSequence ( N , K ) ; } |
Minimum number of bits of array elements required to be flipped to make all array elements equal | C ++ program for the above approach ; Function to count minimum number of bits required to be flipped to make all array elements equal ; Stores the count of unset bits ; Stores the count of set bits ; Traverse the array ; Traverse the bit of arr [ i ] ; If current bit is set ; Increment fre1 [ j ] ; Otherwise ; Increment fre0 [ j ] ; Right shift x by 1 ; Stores the count of total moves ; Traverse the range [ 0 , 32 ] ; Update the value of ans ; Return the minimum number of flips required ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int makeEqual ( int * arr , int n ) { int fre0 [ 33 ] = { 0 } ; int fre1 [ 33 ] = { 0 } ; for ( int i = 0 ; i < n ; i ++ ) { int x = arr [ i ] ; for ( int j = 0 ; j < 33 ; j ++ ) { if ( x & 1 ) { fre1 [ j ] += 1 ; } else { fre0 [ j ] += 1 ; } x = x >> 1 ; } } int ans = 0 ; for ( int i = 0 ; i < 33 ; i ++ ) { ans += min ( fre0 [ i ] , fre1 [ i ] ) ; } return ans ; } int main ( ) { int arr [ ] = { 3 , 5 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << makeEqual ( arr , N ) ; return 0 ; } |
Sum of array elements possible by appending arr [ i ] / K to the end of the array K times for array elements divisible by K | C ++ program for the above approach ; Function to calculate sum of array elements after adding arr [ i ] / K to the end of the array if arr [ i ] is divisible by K ; Stores the sum of the array ; Traverse the array arr [ ] ; Traverse the vector ; If v [ i ] is divisible by K ; Iterate over the range [ 0 , K ] ; Update v ; Otherwise ; Traverse the vector v ; Return the sum of the updated array ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int sum ( int arr [ ] , int N , int K ) { int sum = 0 ; vector < long long > v ; for ( int i = 0 ; i < N ; i ++ ) { v . push_back ( arr [ i ] ) ; } for ( int i = 0 ; i < v . size ( ) ; i ++ ) { if ( v [ i ] % K == 0 ) { long long x = v [ i ] / K ; for ( int j = 0 ; j < K ; j ++ ) { v . push_back ( x ) ; } } else break ; } for ( int i = 0 ; i < v . size ( ) ; i ++ ) sum = sum + v [ i ] ; return sum ; } int main ( ) { int arr [ ] = { 4 , 6 , 8 , 2 } ; int K = 2 ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << sum ( arr , N , K ) ; return 0 ; } |
Check if sum of arr [ i ] / j for all possible pairs ( i , j ) in an array is 0 or not | C ++ program for the above approach ; Function to check if sum of all values of ( arr [ i ] / j ) for all 0 < i <= j < ( N - 1 ) is 0 or not ; Stores the required sum ; Traverse the array ; If the sum is equal to 0 ; Otherwise ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; void check ( int arr [ ] , int N ) { int sum = 0 ; for ( int i = 0 ; i < N ; i ++ ) sum += arr [ i ] ; if ( sum == 0 ) cout << " Yes " ; else cout << " No " ; } int main ( ) { int arr [ ] = { 1 , -1 , 3 , -2 , -1 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; check ( arr , N ) ; return 0 ; } |
Program to calculate expected increase in price P after N consecutive days | C ++ program for the above approach ; Function to find the increased value of P after N days ; Expected value of the number P after N days ; Print the expected value ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; void expectedValue ( int P , int a , int b , int N ) { double expValue = P + ( N * 0.5 * ( a + b ) ) ; cout << expValue ; } int main ( ) { int P = 3000 , a = 20 , b = 10 , N = 30 ; expectedValue ( P , a , b , N ) ; return 0 ; } |
Find the index in a circular array from which prefix sum is always non | C ++ program for the above approach ; Function to find the starting index of the given circular array s . t . prefix sum array is non negative ; Stores the sum of the array ; Stores the starting index ; Stores the minimum prefix sum of A [ 0. . i ] ; Traverse the array arr [ ] ; Update the value of sum ; If sum is less than min ; Update the min as the value of prefix sum ; Update in ; Otherwise , no such index is possible ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int startingPoint ( int A [ ] , int N ) { int sum = 0 ; int in = 0 ; int min = INT_MAX ; for ( int i = 0 ; i < N ; i ++ ) { sum += A [ i ] ; if ( sum < min ) { min = sum ; in = i + 1 ; } } if ( sum < 0 ) { return -1 ; } return in % N ; } int main ( ) { int arr [ ] = { 3 , -6 , 7 , -4 , -4 , 6 , -1 } ; int N = ( sizeof ( arr ) / sizeof ( arr [ 0 ] ) ) ; cout << startingPoint ( arr , N ) ; return 0 ; } |
Modify Linked List by replacing each node by nearest multiple of K | C ++ program for the above approach ; Structure of node ; Function to replace the node N by the nearest multiple of K ; Traverse the Linked List ; If data is less than K ; If the data of current node is same as K ; Otherwise change the value ; Move to the next node ; Return the updated LL ; Function to print the nodes of the Linked List ; Traverse the LL ; Print the node 's data ; Driver Code ; Given Linked List | #include <iostream> NEW_LINE using namespace std ; struct node { int data ; node * next ; } ; node * EvalNearestMult ( node * N , int K ) { node * temp = N ; int t ; while ( N != NULL ) { if ( N -> data < K ) N -> data = 0 ; else { if ( N -> data == K ) N -> data = K ; else { N -> data = ( N -> data / K ) * K ; } } N = N -> next ; } return temp ; } void printList ( node * N ) { while ( N != NULL ) { cout << N -> data << " β " ; N = N -> next ; } } int main ( ) { node * head = NULL ; node * second = NULL ; node * third = NULL ; head = new node ( ) ; second = new node ( ) ; third = new node ( ) ; head -> data = 3 ; head -> next = second ; second -> data = 4 ; second -> next = third ; third -> data = 8 ; third -> next = NULL ; node * t = EvalNearestMult ( head , 3 ) ; printList ( t ) ; return 0 ; } |
Modify array by replacing elements with the nearest power of its previous or next element | C ++ program for the above approach ; Function to calculate the power of y which is nearest to x ; Base Case ; Stores the logarithmic value of x with base y ; Function to replace each array element by the nearest power of its previous or next element ; Stores the previous and next element ; Traverse the array ; Calculate nearest power for previous and next elements ; Replacing the array values ; Print the updated array ; Driver Code ; Given array | #include <bits/stdc++.h> NEW_LINE using namespace std ; int nearestPow ( int x , int y ) { if ( y == 1 ) return 1 ; int k = log10 ( x ) / log10 ( y ) ; if ( abs ( pow ( y , k ) - x ) < abs ( pow ( y , ( k + 1 ) ) - x ) ) return pow ( y , k ) ; return pow ( y , ( k + 1 ) ) ; } void replacebyNearestPower ( vector < int > arr ) { int prev = arr [ arr . size ( ) - 1 ] ; int lastNext = arr [ 0 ] ; int next = 0 ; for ( int i = 0 ; i < arr . size ( ) ; i ++ ) { int temp = arr [ i ] ; if ( i == arr . size ( ) - 1 ) next = lastNext ; else next = arr [ ( i + 1 ) % arr . size ( ) ] ; int prevPow = nearestPow ( arr [ i ] , prev ) ; int nextPow = nearestPow ( arr [ i ] , next ) ; if ( abs ( arr [ i ] - prevPow ) < abs ( arr [ i ] - nextPow ) ) arr [ i ] = prevPow ; else arr [ i ] = nextPow ; prev = temp ; } for ( int i = 0 ; i < arr . size ( ) ; i ++ ) cout << arr [ i ] << " β " ; } int main ( ) { vector < int > arr { 2 , 3 , 4 , 1 , 2 } ; replacebyNearestPower ( arr ) ; } |
Check if sum of array can be made equal to X by removing either the first or last digits of every array element | C ++ program for the above approach ; Utility Function to check if the sum of the array elements can be made equal to X by removing either the first or last digits of every array element ; Base Case ; Convert arr [ i ] to string ; Remove last digit ; Remove first digit ; Recursive function call ; Function to check if sum of given array can be made equal to X or not ; Driver code ; Function Call | #include <bits/stdc++.h> NEW_LINE using namespace std ; bool makeSumX ( int arr [ ] , int X , int S , int i , int N ) { if ( i == N ) { return S == X ; } string a = to_string ( arr [ i ] ) ; int l = stoi ( a . substr ( 0 , a . length ( ) - 1 ) ) ; int r = stoi ( a . substr ( 1 ) ) ; bool x = makeSumX ( arr , X , S + l , i + 1 , N ) ; bool y = makeSumX ( arr , X , S + r , i + 1 , N ) ; return ( x y ) ; } void Check ( int arr [ ] , int X , int N ) { if ( makeSumX ( arr , X , 0 , 0 , N ) ) { cout << " Yes " ; } else { cout << " No " ; } } int main ( ) { int arr [ ] = { 545 , 433 , 654 , 23 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; int X = 134 ; Check ( arr , X , N ) ; return 0 ; } |
Count subarrays having product equal to the power of a given Prime Number | C ++ program for the above approach ; Function to check if y is a power of m or not ; Calculate log y base m and store it in a variable with integer datatype ; Calculate log y base m and store it in a variable with double datatype ; If res1 and res2 are equal , return True . Otherwise , return false ; Function to count the number of subarrays having product of elements equal to a power of m , where m is a prime number ; Stores the count of subarrays required ; Stores current sequence of consecutive array elements which are a multiple of m ; Traverse the array ; If arr [ i ] is a power of M ; Increment cnt ; Update ans ; Update cnt ; Return the count of subarrays ; Driver Code ; Input | #include <bits/stdc++.h> NEW_LINE using namespace std ; bool isPower ( int m , int y ) { int res1 = log ( y ) / log ( m ) ; double res2 = log ( y ) / log ( m ) ; return ( res1 == res2 ) ; } int numSub ( int arr [ ] , int n , int m ) { int ans = 0 ; int cnt = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( isPower ( m , arr [ i ] ) ) { cnt ++ ; ans += ( cnt * ( cnt - 1 ) ) / 2 ; } else { cnt = 0 ; } } return ans ; } int main ( ) { int arr [ ] = { 1 , 1 , 1 , 3 } ; int m = 3 ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << numSub ( arr , n , m ) ; return 0 ; } |
Count pairs whose Bitwise AND exceeds Bitwise XOR from a given array | C ++ program to implement the above approach ; Function to count pairs that satisfy the above condition ; Stores the count of pairs ; Stores the count of array elements having same positions of MSB ; Traverse the array ; Stores the index of MSB of array elements ; Calculate number of pairs ; Driver Code ; Given Input ; Function call to count pairs satisfying the given condition | #include <bits/stdc++.h> NEW_LINE using namespace std ; int cntPairs ( int arr [ ] , int N ) { int res = 0 ; int bit [ 32 ] = { 0 } ; for ( int i = 0 ; i < N ; i ++ ) { int pos = log2 ( arr [ i ] ) ; bit [ pos ] ++ ; } for ( int i = 0 ; i < 32 ; i ++ ) { res += ( bit [ i ] * ( bit [ i ] - 1 ) ) / 2 ; } return res ; } int main ( ) { int arr [ ] = { 1 , 2 , 3 , 4 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << cntPairs ( arr , N ) ; } |
Minimum MEX from all subarrays of length K | C ++ program for the above approach ; Function to return minimum MEX from all K - length subarrays ; Stores element from [ 1 , N + 1 ] which are not present in subarray ; Store number 1 to N + 1 in set s ; Find the MEX of K - length subarray starting from index 0 ; Find the MEX of all subarrays of length K by erasing arr [ i ] and inserting arr [ i - K ] ; Store first element of set ; Updating the mex ; Print minimum MEX of all K length subarray ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; void minimumMEX ( int arr [ ] , int N , int K ) { set < int > s ; for ( int i = 1 ; i <= N + 1 ; i ++ ) s . insert ( i ) ; for ( int i = 0 ; i < K ; i ++ ) s . erase ( arr [ i ] ) ; int mex = * ( s . begin ( ) ) ; for ( int i = K ; i < N ; i ++ ) { s . erase ( arr [ i ] ) ; s . insert ( arr [ i - K ] ) ; int firstElem = * ( s . begin ( ) ) ; mex = min ( mex , firstElem ) ; } cout << mex << ' β ' ; } int main ( ) { int arr [ ] = { 1 , 2 , 3 , 4 , 5 , 6 } ; int K = 3 ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; minimumMEX ( arr , N , K ) ; return 0 ; } |
Count smaller elements present in the array for each array element | C ++ program for the above approach ; Function to count for each array element , the number of elements that are smaller than that element ; Stores the frequencies of array elements ; Traverse the array ; Update frequency of arr [ i ] ; Initialize sum with 0 ; Compute prefix sum of the array hash [ ] ; Traverse the array arr [ ] ; If current element is 0 ; Print the resultant count ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; void smallerNumbers ( int arr [ ] , int N ) { int hash [ 100000 ] = { 0 } ; for ( int i = 0 ; i < N ; i ++ ) hash [ arr [ i ] ] ++ ; int sum = 0 ; for ( int i = 1 ; i < 100000 ; i ++ ) { hash [ i ] += hash [ i - 1 ] ; } for ( int i = 0 ; i < N ; i ++ ) { if ( arr [ i ] == 0 ) { cout << "0" ; continue ; } cout << hash [ arr [ i ] - 1 ] << " β " ; } } int main ( ) { int arr [ ] = { 3 , 4 , 1 , 1 , 2 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; smallerNumbers ( arr , N ) ; return 0 ; } |