Geometric Algorithms
Geometric Algorithms
6 Area of a Hexagon 45
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 48
1
Contents
24 Check if a given circle lies completely inside the ring formed by two
concentric circles 138
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 144
25 Check if a line at 45 degree can divide the plane into two equal weight
parts 145
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 147
2
Contents
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 173
32 Check if right triangle possible from given area and hypotenuse 178
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 183
37 Check whether a given point lies on or inside the rectangle | Set 3 210
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 214
3
Contents
53 Count of acute, obtuse and right triangles with given sides 303
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 306
54 Count of different straight lines with total n points with m collinear 307
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 313
62 Divide cuboid into cubes such that sum of volumes is maximum 354
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 359
4
Contents
72 Find all sides of a right angled triangle from given hypotenuse and area
| Set 1 410
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 413
73 Find an Integer point on a line segment with given two ends 414
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 416
74 Find area of parallelogram if vectors of two adjacent sides are given 417
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 419
79 Find minimum radius such that atleast k point lie inside the circle 438
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 443
5
Contents
88 Find the other end point of a line with given one end and mid 489
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 493
6
Contents
108 Lexicographically Kth smallest way to reach given coordinate from origin597
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 602
7
Contents
116 Maximum number of 2×2 squares that can be fit inside a right isosceles
triangle 646
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 650
118 Maximum number of squares that can fit in a right angle isosceles
triangle 654
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 658
126 Minimum height of a triangle with given base and area 690
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 693
130 Minimum number of square tiles required to fill the rectangular floor 703
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 710
8
Contents
138 Number of Triangles that can be formed given a set of lines in Euclidean
Plane 745
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 749
140 Number of jump required of given length to reach a point of form (d,
0) from origin in 2D plane 758
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 764
143 Number of possible pairs of Hypotenuse and Area to form right angled
triangle 781
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 787
9
Contents
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 811
148 Number of triangles in a plane if no more than two points are collinear818
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 823
159 Probability that the pieces of a broken stick form a n sided polygon 875
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 876
10
Contents
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 896
167 Program for Volume and Surface area of Frustum of Cone 911
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 919
11
Contents
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 993
181 Program to check if tank will overflow, underflow or filled in given time994
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 999
182 Program to check if the points are parallel to X axis or Y axis 1000
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1004
184 Program to check if water tank overflows when n solid balls are dipped
in the water tank 1012
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1019
186 Program to check whether 4 points in a 3-D plane are Coplanar 1034
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1037
188 Program to find third side of triangle using law of cosines 1043
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1049
12
Contents
208 Represent a given set of points by the best possible straight line 1156
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1163
210 Section formula (Point that divides a line in given ratio) 1167
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1172
211 Shortest distance between a Line and a Point in a 3-D plane 1173
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1178
13
Contents
221 Ways to choose three points with distance between the most distant
points <= L 1233
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1239
14
Chapter 1
15
Chapter 1. Angle between two Planes in 3D
16
Chapter 1. Angle between two Planes in 3D
Examples:
Input: a1 = 1, b1 = 1, c1 = 2, d1 = 1, a2 = 2, b2 = -1, c2 = 1, d2 = -4
Output: Angle is is 60.0 degree
Input: a1 = 2, b1 = 2, c1 = -3, d1 = -5, a2 = 3, b2 = -3, c2 = 5, d2 = -6
Output: Angle is 123.696598882 degree
P1 : a1 * x + b1 * y + c1 * z + d1 = 0 and,
P2 : a2 * x + b2 * y + c2 * z + d2 = 0,
where a1, b1, c1, and a2, b2, c2 are direction ratios of normal to the plane P1 and P2.
The angle between two planes is equal to the angle determined by the normal vectors of the
planes.
Angle between these planes is given by using the following formula:-
Cos A =
Using inverse property, we get:
A=
Below is the implementation of the above formulae:
// C program to find
// the Angle between
// two Planes in 3 D.
#include<stdio.h>
#include<math.h>
// Function to find Angle
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);
17
Chapter 1. Angle between two Planes in 3D
Java
18
Chapter 1. Angle between two Planes in 3D
Python
19
Chapter 1. Angle between two Planes in 3D
b2 = -1
c2 = 1
d2 = -4
distance(a1, b1, c1, a2, b2, c2)
C#
// C# program to find
// the Angle between
// two Planes in 3 D.
using System;
class GFG
{
// Function to find Angle
static void distance(float a1, float b1,
float c1, float a2,
float b2, float c2)
{
float d = (a1 * a2 + b1 *
b2 + c1 * c2);
float e1 = (float)Math.Sqrt(a1 * a1 + b1 *
b1 + c1 * c1);
float e2 = (float)Math.Sqrt(a2 * a2 + b2 *
b2 + c2 * c2);
d = d / (e1 * e2);
float pi = (float)3.14159;
float A = (180 / pi) * (float)(Math.Acos(d));
Console.Write(“Angle is “+ A +” degree”);
}
// Driver code
public static void Main()
{
float a1 = 1;
float b1 = 1;
float c1 = 2;
float a2 = 2;
float b2 = -1;
float c2 = 1;
distance(a1, b1, c1,
a2, b2, c2);
}
}
// This code is contributed
// by ChitraNayal
PHP
20
Chapter 1. Angle between two Planes in 3D
<?php
// PHP program to find the Angle
// between two Planes in 3 D.
// Function to find Angle
function distance($a1, $b1,
$c1, $a2,
$b2, $c2)
{
$d = ($a1 * $a2 + $b1 *
$b2 + $c1 * $c2);
$e1 = sqrt($a1 * $a1 + $b1 *
$b1 + $c1 * $c1);
$e2 = sqrt($a2 * $a2 + $b2 *
$b2 + $c2 * $c2);
$d = $d / ($e1 * $e2);
$pi = 3.14159;
$A = (180 / $pi) * (acos($d));
echo sprintf("Angle is %.2f degree", $A);
}
// Driver Code
$a1 = 1;
$b1 = 1;
$c1 = 2;
$d1 = 1;
$a2 = 2;
$b2 = -1;
$c2 = 1;
$d2 = -4;
distance($a1, $b1, $c1,
$a2, $b2, $c2);
// This code is contributed
// by Amber_Saxena.
?>
Output:
Source
https://www.geeksforgeeks.org/angle-between-two-planes-in-3d/
21
Chapter 2
Angular Sweep (Maximum points that can be enclosed in a circle of given radius) - Geeks-
forGeeks
Given ‘n’ points on 2-D plane, find the maximum number of points that can be enclosed by
a fixed-radius circle of radius ‘R’.
Note: The point is considered to be inside the circle even when it lies on the circumference.
Examples:
Input : R = 1
points[] = {(6.47634, 7.69628), (5.16828 4.79915),
(6.69533 6.20378)}
Output : 2
The maximum number of points are 2
Input : R = 1
points[] = {(6.65128, 5.47490), (6.42743, 6.26189)
(6.35864, 4.61611), (6.59020 4.54228), (4.43967 5.70059)
(4.38226, 5.70536), (5.50755 6.18163), (7.41971 6.13668)
(6.71936, 3.04496), (5.61832, 4.23857), (5.99424, 4.29328)
(5.60961, 4.32998), (6.82242, 5.79683), (5.44693, 3.82724)
(6.70906, 3.65736), (7.89087, 5.68000), (6.23300, 4.59530)
(5.92401, 4.92329), (6.24168, 3.81389), (6.22671, 3.62210)}
Output : 11
The maximum number of points are 11
22
Chapter 2. Angular Sweep (Maximum points that can be enclosed in a circle of given
radius)
Naive Algorithm
1. For an arbitrary pair of points in the given set (say A and B), construct the circles
with radius ‘R’ that touches both the points. There are maximum 2 such possible
circles. As we can see here maximum possible circles is for CASE 1 i.e. 2.
2. For each of the constructed circle, check for each point in the set if it lies inside the
circle or not.
3. The circle with maximum number of points enclosed is returned.
Time Complexity: There are n C2 pair of points corresponding to which we can have 2n C2
circles at maximum. For each circle, (n-2) points have to be checked. This makes the naive
algorithm O(n3 ).
23
Chapter 2. Angular Sweep (Maximum points that can be enclosed in a circle of given
radius)
In the given diagram, C1 is the circle with Θ = 0 and C2 is the circle constructed when we
rotate the circle at a general value of Θ.
After this, the problem reduces to, how to maintain the value of count.
For any given point except P (say Q), we can easily calculate the value of Θ for which it
enters the circle (Let it be �) and the value of Θ for which it exits the circle (Let it be �).
We have angles A and B defined as under,
where, x and y represent the coordinates of a point and ‘d’ is the distance between P and
Q.
Now, from the diagrams we can see that,
� = A-B
� = A+B
(Note: All angles are w.r.t. to X-Axis. Thus, it becomes ‘A-B’ and not ‘B-A’).
When Q enters the circle
24
Chapter 2. Angular Sweep (Maximum points that can be enclosed in a circle of given
radius)
We can calculate angles A and B for all points excluding P. Once these angles are found, we
sort them and then traverse them in increasing order. Now we maintain a counter which
tells us how many points are inside the circle at a particular moment.
Count will change only when a point enters the circle or exits it. In case we find an entry
angle we increase the counter by 1 and in case we find an exit angle we decrease the counter
by 1. The check that the angle is entry or exit can be easily realised using a flag.
Proceeding like this, the counter always gives us a valid value for number of points inside
the circle in a particular state.
Important Note: The points which have ‘d’>2R do not have to be considered because
the will never enter or exit the circle.
The angular sweep algorithm can be described as:
1. Calculate the distance between every pair of n C2 points and store them.
2. For an arbitrary point (say P), get the maximum number of points that can lie inside
the circle rotated about P using the getPointsInside() function.
25
Chapter 2. Angular Sweep (Maximum points that can be enclosed in a circle of given
radius)
26
Chapter 2. Angular Sweep (Maximum points that can be enclosed in a circle of given
radius)
// count maintains the number of points inside
// the circle at certain value of theta
// res maintains the maximum of all count
int count = 1, res = 1;
vector<pair<double, bool> >::iterator it;
for (it=angles.begin(); it!=angles.end(); ++it)
{
// entry angle
if ((*it).second)
count++;
// exit angle
else
count--;
if (count > res)
res = count;
}
return res;
}
// Returns count of maximum points that can lie
// in a circle of radius r.
int maxPoints(Point arr[], int n, int r)
{
// dis array stores the distance between every
// pair of points
for (int i=0; i<n-1; i++)
for (int j=i+1; j<n; j++)
// abs gives the magnitude of the complex
// number and hence the distance between
// i and j
dis[i][j] = dis[j][i] = abs(arr[i]-arr[j]);
// This loop picks a point p
int ans = 0;
for (int i=0; i<n; i++)
// maximum number of points for point arr[i]
ans = max(ans, getPointsInside(i, r, n));
return ans;
}
// Driver code
27
Chapter 2. Angular Sweep (Maximum points that can be enclosed in a circle of given
radius)
int main()
{
Point arr[] = {Point(6.47634, 7.69628),
Point(5.16828, 4.79915),
Point(6.69533, 6.20378)};
int r = 1;
int n = sizeof(arr)/sizeof(arr[0]);
cout << "The maximum number of points are: "
<< maxPoints(arr, n, r);
return 0;
}
Output :
Time Complexity: There are n points for which we call the function getPointsInside().
This function works on ‘n-1’ points for which we get 2*(n-1) size of the vector ‘angles’ (one
entry angle and one exit angle). Now this ‘angles’ vector is sorted and traversed which gives
complexity of the getPointsInside() function equal to O(nlogn). This makes the Angular
Sweep Algorithm O(n2 log n).
Related Resources: Using the complex class available in stl for implementing solutions
to geometry problems.
http://codeforces.com/blog/entry/22175
Source
https://www.geeksforgeeks.org/angular-sweep-maximum-points-can-enclosed-circle-given-radius/
28
Chapter 3
Given an angle and the diameter of a circle, we can calculate the length of the arc using the
formula:
Examples :
29
Chapter 3. Arc length from given Angle
Input :
Diameter = 25
Angle = 45
Explanation : ((22/7) * 25) * (45/360)
Output : 9.821 (rounded)
Input :
Diameter = 80
Angle = 60
Explanation : ((22/7) * 80) * (60/360)
Output : 41.905 (rounded)
Note: If angle is greater than or equal to 360 degree, then the arc length cannot be
calculated, since no angle is possible.
C++
30
Chapter 3. Arc length from given Angle
Java
Python3
31
Chapter 3. Arc length from given Angle
# length of an arc
import math
# functuion to calculate arc length
def arcLength(diameter, angle ):
if angle >= 360:
print("Angle cannot be formed")
return 0
else:
arc = (3.142857142857143 * diameter) * (angle / 360.0)
return arc
# Driver Code
diameter = 25.0
angle = 45.0
arc_len = arcLength(diameter, angle)
print(arc_len)
# This code is contributed by "Sharad_Bhardwaj".
C#
32
Chapter 3. Arc length from given Angle
double diameter = 25.0;
double angle = 45.0;
double arc_len = arcLength(diameter, angle);
Console.WriteLine(arc_len);
}
}
// This code is contributed by Anant Agarwal.
PHP
<?php
// PHP program to calculate
// length of an arc
// functuion to calculate
// arc length
function arcLength($diameter,
$angle)
{
$pi = 22.0 / 7.0;
$arc;
if ($angle >= 360)
{
echo "Angle cannot",
" be formed";
return 0;
}
else
{
$arc = ($pi * $diameter) *
($angle / 360.0);
return $arc;
}
}
// Driver Code
$diameter = 25.0;
$angle = 45.0;
$arc_len = arcLength($diameter, $angle);
echo ($arc_len);
// This code is contributed by ajit
?>
33
Chapter 3. Arc length from given Angle
Output:
9.821428571428571
Improved By : jit_t
Source
https://www.geeksforgeeks.org/arc-length-angle/
34
Chapter 4
35
Chapter 4. Area of a Circular Sector
The area of the sector is similar to the calculation of the area of the circle, just multiply
the area of the circle with the angle of the sector.
Examples:
Input:
radius = 9
angle = 60
Explanation:
Sector = ( pi * 9*9 ) * ( 60 / 360 )
Output: 42.42857142857142
Input:
radius = 20
angle = 145
Explanation:
Sector = ( pi * 20*20 ) * ( 145 / 360 )
Output: 506.3492063492063
C++
36
Chapter 4. Area of a Circular Sector
cout<<sector;
}
}
// Driver code
int main()
{
double radius = 9;
double angle = 60;
SectorArea(radius, angle);
return 0;
}
// This code is contributed by Anant Agarwal.
Java
Python3
37
Chapter 4. Area of a Circular Sector
def SectorArea(radius, angle):
pi = 22 / 7
# Constraint or Limit
if angle >= 360:
print("Angle not possible")
return
# Calculating area of the sector
else:
sector = (pi * radius ** 2) * (angle / 360)
print(sector)
return
# Driver code
radius = 9
angle = 60
SectorArea(radius, angle)
C#
38
Chapter 4. Area of a Circular Sector
SectorArea(radius, angle);
}
}
// This code is contributed by vt_m.
PHP
<?php
// PHP program to find Area of a Sector
function SectorArea( $radius, $angle)
{
if($angle >= 360)
echo("Angle not possible");
// Calculating area of the sector
else
{
$sector = ((22 * $radius * $radius)
/ 7) * ($angle / 360);
echo($sector);
}
}
// Driver code
$radius = 9;
$angle = 60;
SectorArea($radius, $angle);
// This code is contributed by vt_m.
?>
Output:
42.42857142857142
Source
https://www.geeksforgeeks.org/area-of-a-sector/
39
Chapter 5
Input : a = 6
Output : Area of a circumscribed circle is : 56.55
Input : a = 4
Output : Area of a circumscribed circle is : 25.13
All four sides of a square are of equal length and all four angles are 90 degree. The circle is
circumscribed on a given square shown by a shaded region in the below diagram.
40
Chapter 5. Area of a Circumscribed Circle of a Square
• The center of the circumcircle is the point where the two diagonals of a square meet.
• Circumscribed circle of a square is made through the four vertices of a square.
• The radius of a circumcircle of a square is equal to the radius of a square.
C++
Java
41
Chapter 5. Area of a Circumscribed Circle of a Square
float PI = 3.14159265f;
return (a * a * (PI / 2));
}
// Driver Function
public static void main(String arg[])
{
float a = 6;
System.out.print("Area of an circumscribed"
+ "circle is :");
System.out.println(areacircumscribed(a));
}
}
// The code is contributed by Anant Agarwal.
Python3
C#
42
Chapter 5. Area of a Circumscribed Circle of a Square
// Driver code
public static void Main()
{
float a = 6;
Console.Write(" Area of an circumscribed"
+ " circle is : {0}",
Math.Round(areacircumscribed(a), 2));
}
}
// This code is contributed by
// Smitha Dinesh Semwal
PHP
<?php
// PHP Program to find the
// area of a circumscribed
// circle
$PI = 3.14159265;
// function returns the area
function areacircumscribed($a)
{
global $PI;
return ($a * $a * ($PI / 2));
}
// Driver code
$a = 6;
echo " Area of an circumscribed circle is : ",
areacircumscribed($a);
// The code is contributed by anuj_67.
?>
Output :
43
Chapter 5. Area of a Circumscribed Circle of a Square
Source
https://www.geeksforgeeks.org/area-circumscribed-circle-square/
44
Chapter 6
Area of a Hexagon
Examples :
Input: 4
Output: 41.5692
Input: 6
Output: 93.5307
Number of vertices: 6
Number of edges: 6
Internal angle: 120°
Area = (3 √3(side)2 ) / 2
45
Chapter 6. Area of a Hexagon
C++
Java
class GFG
{
// Create a function for calculating
// the area of the hexagon.
public static double hexagonArea(double s)
{
return ((3 * Math.sqrt(3) *
(s * s)) / 2);
}
// Driver Code
public static void main(String[] args)
{
// Length of a side
double s = 4;
System.out.print("Area: " +
hexagonArea(s) );
}
}
46
Chapter 6. Area of a Hexagon
C#
// C# program to find
// area of a Hexagon
using System;
class GFG
{
// Create a function for calculating
// the area of the hexagon.
public static double hexagonArea(double s)
{
return ((3 * Math.Sqrt(3) *
(s * s)) / 2);
}
// Driver Code
public static void Main()
{
// Length of a side
double s = 4;
Console.WriteLine("Area: " +
hexagonArea(s) );
}
}
// This code is contributed by vt_m.
PHP
<?php
// PHP program to find
// area of a Hexagon
// function for calculating
// area of the hexagon.
function hexagonArea( $s)
{
return ((3 * sqrt(3) *
($s * $s)) / 2);
}
// Driver Code
// Length of a side
47
Chapter 6. Area of a Hexagon
$s = 4;
echo("Area : ");
echo(hexagonArea($s));
// This code is contributed by vt_m.
?>
Output :
Area: 41.5692
Source
https://www.geeksforgeeks.org/area-of-a-hexagon/
48
Chapter 7
Area
CPP
49
Chapter 7. Area of a polygon with given n ordered vertices
#include <bits/stdc++.h>
using namespace std;
// (X[i], Y[i]) are coordinates of i'th point.
double polygonArea(double X[], double Y[], int n)
{
// Initialze area
double area = 0.0;
// Calculate value of shoelace formula
int j = n - 1;
for (int i = 0; i < n; i++)
{
area += (X[j] + X[i]) * (Y[j] - Y[i]);
j = i; // j is previous vertex to i
}
// Return absolute value
return abs(area / 2.0);
}
// Driver program to test above function
int main()
{
double X[] = {0, 2, 4};
double Y[] = {1, 3, 7};
int n = sizeof(X)/sizeof(X[0]);
cout << polygonArea(X, Y, n);
}
Java
50
Chapter 7. Area of a polygon with given n ordered vertices
int j = n - 1;
for (int i = 0; i < n; i++)
{
area += (X[j] + X[i]) * (Y[j] - Y[i]);
// j is previous vertex to i
j = i;
}
// Return absolute value
return Math.abs(area / 2.0);
}
// Driver program
public static void main (String[] args)
{
double X[] = {0, 2, 4};
double Y[] = {1, 3, 7};
int n = 3;
System.out.println(polygonArea(X, Y, n));
}
}
// This code is contributed by Sunnnysingh
Python3
51
Chapter 7. Area of a polygon with given n ordered vertices
C#
52
Chapter 7. Area of a polygon with given n ordered vertices
}
// This code is contributed by vt_m.
PHP
<?php
// PHP program to evaluate area of
// a polygon using shoelace formula
// (X[i], Y[i]) are
// coordinates of i'th point.
function polygonArea($X, $Y, $n)
{
// Initialze area
$area = 0.0;
// Calculate value of
// shoelace formula
$j = $n - 1;
for ($i = 0; $i < $n; $i++)
{
$area += ($X[$j] + $X[$i]) *
($Y[$j] - $Y[$i]);
// j is previous vertex to i
$j = $i;
}
// Return absolute value
return abs($area / 2.0);
}
// Driver Code
$X = array(0, 2, 4);
$Y = array(1, 3, 7);
$n = sizeof($X);
echo polygonArea($X, $Y, $n);
// This code is contributed by ajit
?>
Output :
53
Chapter 7. Area of a polygon with given n ordered vertices
54
Chapter 7. Area of a polygon with given n ordered vertices
This article is contributed by Utkarsh Trivedi. Please write comments if you find anything
incorrect, or you want to share more information about the topic discussed above
Improved By : jit_t
Source
https://www.geeksforgeeks.org/area-of-a-polygon-with-given-n-ordered-vertices/
55
Chapter 8
Input : r = 3
Output :Area of square = 18
Input :r = 6
Output :Area of square = 72
All four sides of a square are of equal length and all four angles are 90 degree. The circle is
circumscribed on a given square shown by a shaded region in the below diagram.
• The center of the circumcircle is the point where the two diagonals of a square meet.
56
Chapter 8. Area of square Circumscribed by Circle
CPP
57
Chapter 8. Area of square Circumscribed by Circle
return 0;
}
Java
Python3
# Python program to
# find Area of
# square Circumscribed
# by Circle
# Function to find
# area of square
def find_Area(r):
return (2 * r * r)
# driver code
# Radius of a circle
r = 3
58
Chapter 8. Area of square Circumscribed by Circle
# Call Function to find
# an area of square
print(" Area of square = ", find_Area(r))
# This code is contributed
# by Anant Agarwal.
C#
PHP
<?php
// PHP program to find Area of
// square Circumscribed by Circle
// Function to find area of square
function find_Area( $r)
{
return (2 * $r * $r);
59
Chapter 8. Area of square Circumscribed by Circle
}
// Driver code
// Radius of a circle
$r = 3;
// Call Function to find
// an area of square
echo ("Area of square = ");
echo(find_Area($r));
// This code is contributed by vt_m.
?>
Output:
Area of square = 18
Source
https://www.geeksforgeeks.org/area-square-circumscribed-circle/
60
Chapter 9
61
Chapter 9. Bresenham’s Algorithm for 3-D Line Drawing
linearly by 1 along the driving axis and the slope-error variable is used to determine the
change in the co-ordinate values of the other axis.
In case of a 2-D line we use one slope-error variable but in case of a 3-D line we need two
( ) of them for each of the non-driving axes. If current point is (x, y, z) and
the driving axis is the positive X-axis, then the next point could be
• (x+1, y, z)
• (x+1, y+1, z)
• (x+1, y, z+1)
• (x+1, y+1, z+1)
The value of slope-error variables are determined according to the following equations:-
The initial value of slope-error variables are given by the following equations:-
Here denote the difference in co-ordinates of the two end points along
the X, Y, Z axes.
Algorithm:-
62
Chapter 9. Bresenham’s Algorithm for 3-D Line Drawing
2. Plot
3. Calculate constants and determine the driving axis by comparing
• If AND , then
plot and
set
• Else If AND , then
plot and
set
• Else If , then
plot and
set
• Else then
plot and
set >
Python3
63
Chapter 9. Bresenham’s Algorithm for 3-D Line Drawing
64
Chapter 9. Bresenham’s Algorithm for 3-D Line Drawing
p2 += 2 * dz
ListOfPoints.append((x1, y1, z1))
# Driving axis is Z-axis"
else:
p1 = 2 * dy - dz
p2 = 2 * dx - dz
while (z1 != z2):
z1 += zs
if (p1 >= 0):
y1 += ys
p1 -= 2 * dz
if (p2 >= 0):
x1 += xs
p2 -= 2 * dz
p1 += 2 * dy
p2 += 2 * dx
ListOfPoints.append((x1, y1, z1))
return ListOfPoints
def main():
(x1, y1, z1) = (-1, 1, 1)
(x2, y2, z2) = (5, 3, -1)
ListOfPoints = Bresenham3D(x1, y1, z1, x2, y2, z2)
print(ListOfPoints)
main()
Output:
[(-1, 1, 1), (0, 1, 1), (1, 2, 0), (2, 2, 0), (3, 2, 0), (4, 3, -1), (5, 3, -1)]
Source
https://www.geeksforgeeks.org/bresenhams-algorithm-for-3-d-line-drawing/
65
Chapter 10
66
Chapter 10. Calculate Volume and Surface area Of Sphere
Examples :
C++
67
Chapter 10. Calculate Volume and Surface area Of Sphere
{
float sur_ar;
sur_ar = 4 * pi * r * r;
return sur_ar;
}
// Driver Function
int main()
{
float radius = 12;
float vol, sur_area;
// Function Call
vol = volume(radius);
sur_area = surface_area(radius);
// Printing Value Of Volume And Surface Area
cout << "Volume Of Sphere :" << vol << endl;
cout << "Surface Area Of Sphere :" << sur_area << endl;
return 0;
}
Java
68
Chapter 10. Calculate Volume and Surface area Of Sphere
{
float radius = 12;
float vol, sur_area;
// Function Call
vol = volume(radius);
sur_area = surface_area(radius);
// Printing Value Of Volume And Surface Area
System.out.println("Volume Of Sphere :" + vol);
System.out.println("Surface Area Of Sphere :" + sur_area);
}
}
// This code is contributed by Anant Agarwal.
Python3
C#
69
Chapter 10. Calculate Volume and Surface area Of Sphere
PHP
<?php
// CPP program to calculate Volume
// and Surface area of Sphere
70
Chapter 10. Calculate Volume and Surface area Of Sphere
// Function To Calculate
// Volume Of Sphere
function volume( $r)
{
$pi = 3.14159;
$vol = (4 / 3) * $pi * $r * $r * $r;
return $vol;
}
// Function To Calculate
// Surface Area of Sphere
function surface_area( $r)
{
$pi = 3.14159;
$sur_ar = 4 * $pi * $r * $r;
return $sur_ar;
}
// Driver Code
$radius = 12;
$vol; $sur_area;
// Function Call
$vol = volume($radius);
$sur_area = surface_area($radius);
// Printing Value Of
// Volume And Surface Area
echo ("Volume Of Sphere : " );
echo($vol);
echo( " \nSurface Area Of Sphere :");
echo( $sur_area);
// This code is contributed by vt_m.
?>
Output :
Improved By : vt_m
71
Chapter 10. Calculate Volume and Surface area Of Sphere
Source
https://www.geeksforgeeks.org/calculate-volume-surface-area-sphere/
72
Chapter 11
Calculate Volume of
Dodecahedron
Input : side = 4
Output : 490.44
Input : side = 9
Output : 5586.41
C++
73
Chapter 11. Calculate Volume of Dodecahedron
{
return (((15 + (7 * (sqrt(5)))) / 4)
* (pow(side, 3))) ;
}
// Driver Function
int main()
{
int side = 4;
cout << "Volume of dodecahedron = "
<< vol_of_dodecahedron(side);
}
Java
Python3
74
Chapter 11. Calculate Volume of Dodecahedron
def vol_of_dodecahedron(side) :
return (((15 + (7 * (math.sqrt(5)))) / 4)
* (math.pow(side, 3)))
# Driver Function
side = 4
print("Volume of dodecahedron =",
round(vol_of_dodecahedron(side), 2))
# This code is contributed by Smitha Dinesh Semwal
C#
// C# program to calculate
// Volume of dodecahedron
using System;
public class GFG
{
// utility Function
static float vol_of_dodecahedron(int side)
{
return (float)(((15 + (7 * (Math.Sqrt(5)))) / 4)
* (Math.Pow(side, 3))) ;
}
// Driver Function
static public void Main ()
{
int side = 4;
Console.WriteLine("Volume of dodecahedron = "
+ vol_of_dodecahedron(side));
}
}
/* This code is contributed by vt_m.*/
PHP
<?php
// PHP program to calculate
// Volume of dodecahedron
75
Chapter 11. Calculate Volume of Dodecahedron
// utility Function
function vol_of_dodecahedron($side)
{
return (((15 + (7 * (sqrt(5)))) / 4)
* (pow($side, 3))) ;
}
// Driver Function
$side = 4;
echo ("Volume of dodecahedron = ");
echo(vol_of_dodecahedron($side));
// This code is contributed by vt_m.
?>
Output :
Improved By : vt_m
Source
https://www.geeksforgeeks.org/calculate-volume-dodecahedron/
76
Chapter 12
Cone :
Cone is a three dimensional geometric shape. It consists of a base having the shape of a
circle and a curved side (the lateral surface) ending up in a tip called the apex or vertex.
Volume of a cone :
The volume of a cone is given by the formula –
volume = 1/3(pi * r * r * h)
where r is the radius of the circular base, and h is the height (the perpendicular distance
from the base to the vertex).
Surface area of a cone :
The surface area of a cone is given by the formula –
77
Chapter 12. Calculate volume and surface area of a cone
area = pi * r * s + pi * r^2
Where r is the radius of the circular base, and s is the slant height of the cone.
Examples :
Input :
radius = 5
slant_height = 13
height = 12
Output :
Volume Of Cone = 314.159
Surface Area Of Cone = 282.743
Input :
radius = 6
slant_height = 10
height = 8
Output :
Volume Of Cone = 301.593
Surface Area Of Cone = 301.593
C++
78
Chapter 12. Calculate volume and surface area of a cone
int main()
{
float radius = 5;
float slant_height = 13;
float height = 12;
float vol, sur_area;
// Printing value of volume
// and surface area
cout << "Volume Of Cone : "
<< volume(radius, height) << endl;
cout << "Surface Area Of Cone : "
<< surface_area(radius, slant_height);
return 0;
}
Java
79
Chapter 12. Calculate volume and surface area of a cone
// Printing value of volume
// and surface area
System.out.print("Volume Of Cone : ");
System.out.println(volume(radius, height));
System.out.print("Surface Area Of Cone : ");
System.out.println(surface_area(radius,
slant_height));
}
}
// This code is contributed by "akanshgupta"
Python
C#
// C# program to calculate
// Volume and Surface area of cone
using System;
class GFG
{
80
Chapter 12. Calculate volume and surface area of a cone
PHP
<?php
// PHP program to calculate Volume
// and Surface area of Cone
81
Chapter 12. Calculate volume and surface area of a cone
Output :
Improved By : vt_m
Source
https://www.geeksforgeeks.org/calculate-volume-surface-area-cone/
82
Chapter 13
Input : 3
Output : 37
Input : 7
Output :253
83
Chapter 13. Centered Dodecagonal Number
C++
Java
84
Chapter 13. Centered Dodecagonal Number
return 6 * n * (n - 1) + 1;
}
// Driver Code
public static void main (String[] args)
{
long n = 2;
System.out.println(centeredDodecagonal(n));
n = 9;
System.out.println(centeredDodecagonal(n));
}
}
// This code is contributed by anuj_67.
Output :
13
433
References
http://oeis.org/A003154
Improved By : vt_m
Source
https://www.geeksforgeeks.org/centered-dodecagonal-number/
85
Chapter 14
Centered Octadecagonal
Number
Examples :
Input : 2
Output : 19
Input : 6
Output : 271
86
Chapter 14. Centered Octadecagonal Number
Java
87
Chapter 14. Centered Octadecagonal Number
Python3
88
Chapter 14. Centered Octadecagonal Number
center_octadecagon_num(n))
n = 13
print(n,"th centered octadecagonal " +
"number : ",
center_octadecagon_num(n))
# This code is contributed
# by akt_mit
C#
PHP
89
Chapter 14. Centered Octadecagonal Number
<?php
// PHP Program to find the
// nth centered octadecagonal
// number
// centered octadecagon function
function center_octadecagon_num($n)
{
// Formula to calculate nth
// centered octadecagonal number
return (9 * $n * $n -
9 * $n + 1);
}
// Driver Code
$n = 3;
echo $n , "th centered octadecagonal " .
"number : ",
center_octadecagon_num($n);
echo "\n";
$n = 13;
echo $n , "th centered octadecagonal " .
"number : ",
center_octadecagon_num($n);
// This code is contributed by m_kit
?>
Output :
Improved By : jit_t
Source
https://www.geeksforgeeks.org/centered-octadecagonal-number/
90
Chapter 15
Examples :
Input : 2
Output : 9
Input : 5
Output : 81
91
Chapter 15. Centered Octagonal Number
C++
Java
92
Chapter 15. Centered Octagonal Number
Python3
93
Chapter 15. Centered Octagonal Number
cen_octagonalnum(n))
n = 11
print(n,"th Centered" ,
"octagonal number: ",
cen_octagonalnum(n))
# This code is contributed
# by akt_mit
C#
PHP
<?php
94
Chapter 15. Centered Octagonal Number
Output
Source
https://www.geeksforgeeks.org/centered-octagonal-number/
95
Chapter 16
Centered Pentadecagonal
Number
Examples :
Input : 2
Output : 16
Input : 8
Output : 421
96
Chapter 16. Centered Pentadecagonal Number
Java
97
Chapter 16. Centered Pentadecagonal Number
Python3
98
Chapter 16. Centered Pentadecagonal Number
C#
// C# Program to find
// nth centered
// pentadecagonal number
using System;
class GFG
{
// centered
// pentadecagonal function
static long center_pentadecagonal_num(long n)
{
// Formula to calculate
// nth centered
// pentadecagonal number
return (15 * n * n -
15 * n + 2) / 2;
}
// Driver Code
static public void Main ()
{
long n = 3;
Console.Write(n + "th number : ");
Console.WriteLine(
center_pentadecagonal_num(n));
n = 10;
Console.Write( n + "th number : ");
Console.WriteLine(
center_pentadecagonal_num(n));
}
}
// This code is contributed by ajit.
PHP
<?php
// PHP Program to find
// nth centered
// pentadecagonal number
99
Chapter 16. Centered Pentadecagonal Number
// centered pentadecagonal function
function center_pentadecagonal_num($n)
{
// Formula to calculate nth
// centered pentadecagonal number
return (15 * $n * $n -
15 * $n + 2) / 2;
}
// Driver Code
$n = 3;
echo $n , "th number : ",
center_pentadecagonal_num($n);
echo "\n";
$n = 10;
echo $n , "th number : ",
center_pentadecagonal_num($n);
// This code is contributed by m_kit
?>
Output :
3th number : 46
10th number : 676
Improved By : jit_t
Source
https://www.geeksforgeeks.org/centered-pentadecagonal-number/
100
Chapter 17
Input : n = 1
Output : 9
Input : n = 7
Output : 855
101
Chapter 17. Centered cube number
// Function to find
// Centered cube number
int centered_cube(int n)
{
// Formula to calculate nth
// Centered cube number &
// return it into main function.
return (2 * n + 1) * ( n * n + n + 1);
}
// Driver Code
int main()
{
int n = 3;
cout << n << "th Centered cube number: ";
cout << centered_cube(n);
cout << endl;
n = 10;
cout << n << "th Centered cube number: ";
cout << centered_cube(n);
return 0;
}
Java
102
Chapter 17. Centered cube number
Python3
C#
103
Chapter 17. Centered cube number
using System;
class GFG
{
// Function to find
// Centered cube number
static int centered_cube(int n)
{
// Formula to calculate
// nth Centered cube
// number & return it
// into main function.
return (2 * n + 1) *
(n * n + n + 1);
}
// Driver code
static public void Main ()
{
int n = 3;
Console.Write(n + "th Centered" +
" cube number: ");
Console.WriteLine (centered_cube(n));
n = 10;
Console.Write( n + "th Centered" +
" cube number: ");
Console.WriteLine(centered_cube(n));
}
}
// This code is contributed by aj_36
PHP
<?php
// Program to find nth
// Centered cube number
// Function to find
// Centered cube number
function centered_cube($n)
{
// Formula to calculate nth
// Centered cube number &
// return it into main function.
return (2 * $n + 1) *
104
Chapter 17. Centered cube number
($n * $n + $n + 1);
}
// Driver Code
$n = 3;
echo $n , "th Centered cube number: ";
echo centered_cube($n);
echo "\n";
$n = 10;
echo $n , "th Centered cube number: ";
echo centered_cube($n);
// This code is contributed by m_kit
?>
Output :
Improved By : jit_t
Source
https://www.geeksforgeeks.org/centered-cube-number/
105
Chapter 18
Input : 3
Output : 31
106
Chapter 18. Centered decagonal number
Input : 6
Output : 151
Java
107
Chapter 18. Centered decagonal number
Python 3
108
Chapter 18. Centered decagonal number
5 * n + 1)
# Driver Code
if __name__ == '__main__' :
n = 5
print(n,"th centered decagonal " +
"number : ",
centereddecagonalnum(n))
n = 9
print(n,"th centered decagonal " +
"number : ",
centereddecagonalnum(n))
# This code is contributed by m_kit
C#
109
Chapter 18. Centered decagonal number
}
}
// This code is contributed by aj_36
PHP
<?php
// Program to find nth
// centered decagonal number
// Centered decagonal
// number function
function centereddecagonalnum($n)
{
// Formula to calculate
// nth centered decagonal
// number & return it
// into main function.
return (5 * $n * $n +
5 * $n + 1);
}
// Driver Code
$n = 5;
echo $n , "th centered decagonal",
"number: ";
echo centereddecagonalnum($n);
echo "\n";
$n = 9;
echo $n , "th centered decagonal",
"number: ";
echo centereddecagonalnum($n);
// This code is contributed by ajit
?>
Output
Improved By : jit_t
110
Chapter 18. Centered decagonal number
Source
https://www.geeksforgeeks.org/centered-decagonal-number/
111
Chapter 19
Input : 5
Output : 1661
Input :1
Output :33
Mathematical formula for the nth Centered dodecahedral number is given by:
112
Chapter 19. Centered dodecahedral number
// Function to find
// centered dodecahedral number
int CenteredDodecahedral_num(long int n)
{
// Formula to calculate nth
// centered dodecahedral number
// and return it into main function.
return (2 * n + 1) * (5 * n * n + 5 * n + 1);
}
// Driver Code
int main()
{
long int n = 3;
// print result
cout << n << "th Centered Dodecahedral number : ";
cout << CenteredDodecahedral_num(n) << endl;
n = 10;
// print result
cout << n << "th Centered Dodecahedral number : ";
cout << CenteredDodecahedral_num(n);
return 0;
}
Java
113
Chapter 19. Centered dodecahedral number
{
int n = 3;
// print result
System.out.print( n + "th Centered "
+ "Dodecahedral number : ");
System.out.println (
CenteredDodecahedral_num(n));
n = 10;
// print result
System.out.print( n + "th Centered "
+ "Dodecahedral number : ");
System.out.println(
CenteredDodecahedral_num(n));
}
}
// This code is contributed by m_kit.
Python3
C#
114
Chapter 19. Centered dodecahedral number
// C# Program to find
// nth centered
// dodecahedral number
using System;
class GFG
{
// Function to find
// nth centered
// dodecahedral number
static int CenteredDodecahedral_num(int n)
{
// Formula to calculate
// nth centered dodecahedral
// number and return it
// into main function.
return (2 * n + 1) *
(5 * n * n +
5 * n + 1);
}
// Driver Code
static public void Main ()
{
int n = 3;
// print result
Console.Write( n + "th Centered " +
"Dodecahedral number : ");
Console.WriteLine(
CenteredDodecahedral_num(n));
n = 10;
// print result
Console.Write( n + "th Centered " +
"Dodecahedral number : ");
Console.WriteLine(
CenteredDodecahedral_num(n));
}
}
// This code is contributed by ajit
PHP
115
Chapter 19. Centered dodecahedral number
<?php
// Program to find nth centered
// dodecahedral number
// Function to find
// centered dodecahedral number
function CenteredDodecahedral_num($n)
{
// Formula to calculate nth
// centered dodecahedral number
// and return it into main function.
return (2 * $n + 1) *
(5 * $n * $n +
5 * $n + 1);
}
// Driver Code
$n = 3;
// print result
echo $n, "th Centered Dodecahedral " .
"number : ";
echo CenteredDodecahedral_num($n),"\n";
$n = 10;
// print result
echo $n, "th Centered Dodecahedral " .
"number : ";
echo CenteredDodecahedral_num($n);
// This code is contributed by akt_mit
?>
Output :
References:
https://en.wikipedia.org/wiki/Centered_dodecahedral_number
Improved By : jit_t
Source
https://www.geeksforgeeks.org/centered-dodecahedral-number/
116
Chapter 20
Centered nonadecagonal
number
Input : 3
Output : 58
117
Chapter 20. Centered nonadecagonal number
Input : 13
Output :1483
Java
118
Chapter 20. Centered nonadecagonal number
class GFG {
// centered nonadecagonal
// function
static int center_nonadecagon_num(int n)
{
// Formula to calculate nth
// centered nonadecagonal number
return (19 * n * n - 19 * n + 2) / 2;
}
// Driver code
public static void main (String[] args)
{
int n = 2;
System.out.print ( n + "th centered "
+ "nonadecagonal number : ");
System.out.println (
center_nonadecagon_num(n));
n = 7;
System.out.print ( n + "th centered "
+ "nonadecagonal number : ");
System.out.println(
center_nonadecagon_num(n));
}
}
// This code is contributed by m_kit
Python3
119
Chapter 20. Centered nonadecagonal number
C#
// C# Program to find
// nth centered
// nonadecagonal number
using System;
class GFG
{
// centered nonadecagonal
// function
static int center_nonadecagon_num(int n)
{
// Formula to calculate nth
// centered nonadecagonal number
return (19 * n * n -
19 * n + 2) / 2;
}
// Driver code
static public void Main ()
{
int n = 2;
Console.Write ( n + "th centered " +
"nonadecagonal number : ");
Console.WriteLine(
center_nonadecagon_num(n));
n = 7;
Console.Write( n + "th centered " +
"nonadecagonal number : ");
Console.WriteLine(
center_nonadecagon_num(n));
}
}
120
Chapter 20. Centered nonadecagonal number
// This code is contributed by ajit
PHP
<?php
// PHP Program to find
// nth centered
// nonadecagonal number
// centered nonadecagonal
// function
function center_nonadecagon_num( $n )
{
// Formula to calculate nth
// centered nonadecagonal number
return (19 * $n * $n -
19 * $n + 2) / 2;
}
// Driver Code
$n = 2;
echo $n ,"th centered " +
"nonadecagonal number : ",
center_nonadecagon_num($n);
echo "\n";
$n = 7;
echo $n , "th centered " +
"nonadecagonal number : ",
center_nonadecagon_num($n);
// This code is contributed by ajit
?>
Output :
References:
http://oeis.org/A069132
Improved By : jit_t
Source
https://www.geeksforgeeks.org/centered-nonadecagonal-number/
121
Chapter 21
122
Chapter 21. Centered pentagonal number
Input : 3
Output : 16
Input : 9
Output : 181
Approach:
Centered pentagonal for n-th term is given by :
123
Chapter 21. Centered pentagonal number
C++
Java
124
Chapter 21. Centered pentagonal number
return (5 * n * n - 5 * n + 2) / 2;
}
// Driver Code
public static void main (String[] args)
{
int n = 7;
System.out.print(n + "th Centered " +
"pentagonal number: ");
System.out.println(centered_pentagonal_Num(n));
}
}
// This code is contributed by anuj_67.
Python3
C#
125
Chapter 21. Centered pentagonal number
// number function
static int centered_pentagonal_Num(int n)
{
// Formula to calculate
// nth Centered pentagonal
// number and return it
// into main function.
return (5 * n * n - 5 * n + 2) / 2;
}
// Driver Code
public static void Main ()
{
int n = 7;
Console.Write(n + "th Centered " +
"pentagonal number: ");
Console.WriteLine(centered_pentagonal_Num(n));
}
}
// This code is contributed by anuj_67.
PHP
<?php
// PHP Program to find nth
// Centered pentagonal number.
// Centered pentagonal number function
function centered_pentagonal_Num($n)
{
// Formula to calculate nth
// Centered pentagonal number
// and return it into main function.
return (5 * $n * $n - 5 * $n + 2) / 2;
}
// Driver Code
$n = 7;
echo $n , "th Centered pentagonal number: ";
echo centered_pentagonal_Num($n);
// This code is contributed by aj_36
?>
126
Chapter 21. Centered pentagonal number
Output :
Source
https://www.geeksforgeeks.org/centered-pentagonal-number/
127
Chapter 22
Input : 2
Output : 14
Input : 9
Output : 469
128
Chapter 22. Centered tridecagonal number
C++
Java
129
Chapter 22. Centered tridecagonal number
}
// Driver Code
public static void main (String[] args)
{
long n = 3;
System.out.println(centeredTridecagonalNum(n));
n = 10;
System.out.println(centeredTridecagonalNum(n));
}
}
// This code is contributed by anuj_67.
Python3
C#
130
Chapter 22. Centered tridecagonal number
// Function to find nth centered
// tridecagonal number
static long centeredTridecagonalNum(long n)
{
// Formula to calculate nth
// centered tridecagonal number
return (13 * n * (n - 1) + 2) / 2;
}
// Driver Code
public static void Main ()
{
long n = 3;
Console.WriteLine(centeredTridecagonalNum(n));
n = 10;
Console.WriteLine(centeredTridecagonalNum(n));
}
}
// This code is contributed by anuj_67.
PHP
<?php
// PHP Program to find nth
// centered tridecagonal number
// Function to find nth centered
// tridecagonal number
function centeredTridecagonalNum( $n)
{
// Formula to calculate nth
// centered tridecagonal number
return (13 * $n *
($n - 1) + 2) / 2;
}
// Driver Code
$n = 3;
echo centeredTridecagonalNum($n);
echo"\n";
$n = 10;
echo centeredTridecagonalNum($n);
// This code is contributed by anuj_67.
?>
131
Chapter 22. Centered tridecagonal number
Output :
40
586
Reference: http://oeis.org/wiki/Figurate_numbers
Improved By : vt_m, jit_t
Source
https://www.geeksforgeeks.org/centered-tridecagonal-number/
132
Chapter 23
133
Chapter 23. Chain Code for 2D Line
The chain codes could be generated by using conditional statements for each direction but
it becomes very tedious to describe for systems having large number of directions(3-D grids
can have up to 26 directions). Instead we use a hash function. The difference in X( )
and Y( ) co-ordinates of two successive points are calculated and hashed to generate the
key for the chain code between the two points.
Hash function:
Hash table:-
1 0 5 0
1 1 8 1
0 1 7 2
-1 1 6 3
-1 0 3 4
-1 -1 0 5
134
Chapter 23. Chain Code for 2D Line
0 -1 1 6
1 -1 2 7
The function does not generate the value 4 so a dummy value is stored there.
Examples:
Python3
135
Chapter 23. Chain Code for 2D Line
136
Chapter 23. Chain Code for 2D Line
DriverFunction()
Output:
Chain code for the straight line from (-9, -3) to (10, 1) is 0010000100010000100
Source
https://www.geeksforgeeks.org/chain-code-for-2d-line/
137
Chapter 24
Check if a given circle lies completely inside the ring formed by two concentric circles -
GeeksforGeeks
Given two circles of radius r and R, both have their centre at the origin. Now, given another
circle of radius r1 and centre at (x1, y1). Check, if the third circle(circle of radius r1) lies
completely inside the ring formed by two circles of radius r and R.
Examples :
Input : r = 8 R = 4
r1 = 2 x1 = 6 y1 = 0
Output : yes
Input : r = 8 R = 4
r1 = 2 x1 = 5 y1 = 0
Output : no
Important : Concentric circles are those circles which have same centre. The region lying
between two concentric circles is called annulus or the circular ring.
138
Chapter 24. Check if a given circle lies completely inside the ring formed by two
concentric circles
Example :
There are two concentric circles with their centre at origin(0, 0) and radius as r = 8 and R
= 4.
1.) Circle 1 and 2 lies inside the ring.
2.) Circle 3 and 4 are outside the ring.
The complete figure can be visualised as given below :
139
Chapter 24. Check if a given circle lies completely inside the ring formed by two
concentric circles
Approach :
This problem can be solved using Pythagoras Theorem . Compute the distance between
the centre of the circle and origin using Pythagoras theorem, suppose it is denoted by ‘dis’.
After computing the distance just check that the value of (dis – r1)> = r and (dis + r1)<
= R. If both these conditions hold then the circle lies completely inside the ring.
C++
140
Chapter 24. Check if a given circle lies completely inside the ring formed by two
concentric circles
Java
141
Chapter 24. Check if a given circle lies completely inside the ring formed by two
concentric circles
Python3
142
Chapter 24. Check if a given circle lies completely inside the ring formed by two
concentric circles
C#
// C# code to check if a
// circle lies in the ring
using System;
class ring {
// Function to check if circle
// lies in the ring
public static bool checkcircle(int r, int R,
int r1, int x1, int y1)
{
// distance between center of circle
// center of concentric circles(origin)
// using Pythagoras theorem
int dis = (int)Math.Sqrt(x1 * x1 + y1 * y1);
// Condition to check if circle
// is strictly inside the ring
return (dis - r1 >= R && dis + r1 <= r);
}
// Driver Code
public static void Main()
{
// Both circle with radius 'r'
// and 'R' have center (0, 0)
int r = 8, R = 4, r1 = 2, x1 = 6, y1 = 0;
if (checkcircle(r, R, r1, x1, y1))
Console.WriteLine("yes");
else
Console.WriteLine("no");
}
}
// This code is contributed by vt_m.
PHP
<?php
// PHP code to check if a circle
// lies in the ring
// Function to check if circle
// lies in the ring
143
Chapter 24. Check if a given circle lies completely inside the ring formed by two
concentric circles
Output:
yes
Improved By : jit_t
Source
https://www.geeksforgeeks.org/check-given-circle-lies-completely-inside-ring-formed-two-concentric-circles/
144
Chapter 25
Check if a line at 45 degree can divide the plane into two equal weight parts - GeeksforGeeks
Given a set of n points (xi , yi ) in 2D coordinate. Each point has some weight wi . The
task is to check whether a line at 45 degree can be drawn so that sum of weights of points
on each side are equal.
Examples:
Input : x1 = -1, y1 = 1, w1 = 3
x2 = -2, y2 = 1, w2 = 1
x3 = 1, y3 = -1, w3 = 4
Output : Yes
Input : x1 = 1, y1 = 1, w1 = 2
x2 = -1, y2 = 1, w2 = 1
x3 = 1, y3 = -1, w3 = 2
Output : No
First, let’s try to solve above problem for a vertical line i.e if a line x = i can divide the
plane into two part such that the sum of weight at each side is equal.
Observe, multiple points with the same x-coordinate can be treated as one point with weight
equal to the sum of weights of all points with the same x-coordinate.
Now, traverse through all x-coordinates from the minimum x-coordinate to maximum x-
coordinate. So, make an array prefix_sum[], which will store the sum of weights till the
145
Chapter 25. Check if a line at 45 degree can divide the plane into two equal weight parts
point x = i.
So, there can be two options for which the answer can be ‘Yes’:
Now, to solve for a line at 45 degrees, we will rotate each point by 45 degrees.
Refer: 2D Transformation or Rotation of objects
So, point at (x, y), after 45 degree rotation will become ((x – y)/sqrt(2), (x + y)/sqrt(2)).
We can ignore the sqrt(2) since it is the scaling factor. Also, we don’t need to care about y-
coordinate after rotation because a vertical line cannot distinguish between the point having
the same x-coordinate. (x, y1 ) and (x, y2 ) will lie to the right, left or on any line of the
form x = k.
#include <bits/stdc++.h>
using namespace std;
// Checking if a plane can be divide by a line
// at 45 degrees such that weight sum is equal
void is_partition_possible(int n, int x[],
int y[], int w[])
{
map<int, int> weight_at_x;
int max_x = -2e3, min_x = 2e3;
// Rotating each point by 45 degrees and
// calculating prefix sum.
// Also, finding maximum and minimum x
// coordinates
for (int i = 0; i < n; i++) {
int new_x = x[i] - y[i];
max_x = max(max_x, new_x);
min_x = min(min_x, new_x);
// storing weight sum upto x - y point
weight_at_x[new_x] += w[i];
146
Chapter 25. Check if a line at 45 degree can divide the plane into two equal weight parts
}
vector<int> sum_till;
sum_till.push_back(0);
// Finding prefix sum
for (int x = min_x; x <= max_x; x++) {
sum_till.push_back(sum_till.back() +
weight_at_x[x]);
}
int total_sum = sum_till.back();
int partition_possible = false;
for (int i = 1; i < sum_till.size(); i++) {
if (sum_till[i] == total_sum - sum_till[i])
partition_possible = true;
// Line passes through i, so it neither
// falls left nor right.
if (sum_till[i - 1] == total_sum - sum_till[i])
partition_possible = true;
}
printf(partition_possible ? "YES\n" : "NO\n");
}
// Driven Program
int main()
{
int n = 3;
int x[] = { -1, -2, 1 };
int y[] = { 1, 1, -1 };
int w[] = { 3, 1, 4 };
is_partition_possible(n, x, y, w);
return 0;
}
Output
Yes
Source
https://www.geeksforgeeks.org/check-if-a-line-at-45-degree-can-divide-the-plane-into-two-equal-weight-parts/
147
Chapter 26
Examples:
148
Chapter 26. Check if a line passes through the origin
Approach: Equation of a line passing through two points (x1, y1) and (x2, y2) is given by
y-y1 = ((y2-y1) / (x2-x1))(x-x1) + c
If line is also passing through origin, then c=0, so equation of line becomes
y-y1 = ((y2-y1) / (x2-x1))(x-x1)
Keeping x=0, y=0 in the above equation we get,
x1(y2-y1) = y1(x2-x1)
So above equation must be satisfied if any line passing through two coordinates (x1, y1) and
(x2, y2) also passes through origin (0, 0).
C++
Java
149
Chapter 26. Check if a line passes through the origin
}
// Driver code
public static void main (String[] args)
{
if (checkOrigin(1, 28, 2, 56) == true)
System.out.println("Yes");
else
System.out.println("No");
}
}
// This code is contributed by Ajit.
Python3
C#
150
Chapter 26. Check if a line passes through the origin
PHP
<?php
// PHP program to find if
// line passing through
// two coordinates also
// passes through origin
// or not
function checkOrigin($x1, $y1,
$x2, $y2)
{
return ($x1 * ($y2 - $y1) ==
$y1 * ($x2 - $x1));
}
// Driver code
if (checkOrigin(1, 28, 2, 56) == true)
echo("Yes");
else
echo("No");
// This code is contributed by Ajit.
?>
Output:
Yes
Improved By : jit_t
Source
https://www.geeksforgeeks.org/check-line-passes-origin/
151
Chapter 27
Note: General equation of a line is a*x + b*y + c = 0, so only constant a, b, c are given in
the input.
Examples :
152
Chapter 27. Check if a line touches or intersects a circle
The idea is to compare the perpendicular distance between center of circle and line with the
radius of the circle.
Algorithm:
1. Find the perpendicular (say p) between center of circle and given line.
2. Compare this distance p with radius r.
……a) If p > r, then line lie outside the circle.
……b) If p = r, then line touches the circle.
……c) If p < r, then line intersect the circle.
How to find the perpendicular distance ?
Distance of a line from a point can be computed using below formula:
C++
153
Chapter 27. Check if a line touches or intersects a circle
Java
154
Chapter 27. Check if a line touches or intersects a circle
checkCollision(a, b, c, x, y, radius);
}
}
// This article is contributed by vt_m.
Python3
C#
155
Chapter 27. Check if a line touches or intersects a circle
class GFG {
static void checkCollision(int a, int b, int c,
int x, int y, int radius)
{
// Finding the distance of line from center.
double dist = (Math.Abs(a * x + b * y + c)) /
Math.Sqrt(a * a + b * b);
// Checking if the distance is less than,
// greater than or equal to radius.
if (radius == dist)
Console.WriteLine ("Touch");
else if (radius > dist)
Console.WriteLine("Intersect");
else
Console.WriteLine("Outside");
}
// Driven Program
public static void Main ()
{
int radius = 5;
int x = 0, y = 0;
int a = 3, b = 4, c = 25;
checkCollision(a, b, c, x, y, radius);
}
}
// This article is contributed by vt_m.
PHP
<?php
// PHP program to check if a line
// touches or intersects or outside
// a circle.
function checkCollision($a, $b, $c,
$x, $y, $radius)
{
// Finding the distance
// of line from center.
$dist = (abs($a * $x + $b * $y + $c)) /
sqrt($a * $a + $b * $b);
156
Chapter 27. Check if a line touches or intersects a circle
// Checking if the distance is less than,
// greater than or equal to radius.
if ($radius == $dist)
echo "Touch";
else if ($radius > $dist)
echo "Intersect";
else
echo "Outside" ;
}
// Driver Code
$radius = 5;
$x = 0;
$y = 0;
$a = 3;
$b = 4;
$c = 25;
checkCollision($a, $b, $c, $x, $y, $radius);
// This code is contributed by Sam007
?>
Output :
Touch
Improved By : Sam007
Source
https://www.geeksforgeeks.org/check-line-touches-intersects-circle/
157
Chapter 28
This problem is already discussed in a previous post. In this post we have discussed a new
approach.
Approach: The above problem can be solved by observation. A point lies inside or not the
rectangle if and only if it’s x-coordinate lies between the x-coordinate of the given bottom-
right and top-left coordinates of the rectangle and y-coordinate lies between the y-coordinate
of the given bottom-right and top-left coordinates.
Below is the implementation of the above approach:
C++
158
Chapter 28. Check if a point lies on or inside a rectangle | Set-2
Java
// Java program to Check if
// a point lies on or inside
// a rectangle | Set-2
class GFG
{
// function to find if given point
// lies inside a given rectangle or not.
static boolean FindPoint(int x1, int y1, int x2,
int y2, int x, int y)
{
if (x > x1 && x < x2 && y > y1 && y < y2) return true; return false; } // Driver code
public static void main(String[] args) { // bottom-left and top-right // corners of rectangle
int x1 = 0, y1 = 0, x2 = 10, y2 = 8; // given point int x = 1, y = 5; // function call if
(FindPoint(x1, y1, x2, y2, x, y)) System.out.println(”Yes”); else System.out.println(”No”);
} } // This code is contributed // by ChitraNayal [tabby title=”Python3”]
159
Chapter 28. Check if a point lies on or inside a rectangle | Set-2
C#
// C# program to Check if a
// point lies on or inside
// a rectangle | Set-2
using System;
class GFG
{
// function to find if given
// point lies inside a given
// rectangle or not.
static bool FindPoint(int x1, int y1, int x2,
160
Chapter 28. Check if a point lies on or inside a rectangle | Set-2
<?php
// PHP program to Check if
// a point lies on or inside
// a rectangle | Set-2
// function to find if given
// point lies inside a given
// rectangle or not.
function FindPoint($x1, $y1, $x2,
$y2, $x, $y)
{
if ($x > $x1 and $x < $x2 and
$y > $y1 and $y < $y2)
return true;
return false;
}
// Driver code
// bottom-left and top-right
// corners of rectangle
$x1 = 0; $y1 = 0;
$x2 = 10; $y2 = 8;
// given point
$x = 1; $y = 5;
// function call
if (FindPoint($x1, $y1, $x2,
$y2, $x, $y))
echo "Yes";
else
echo "No";
// This code is contributed
// by Akanksha Rai(Abby_akku)
?>
Output:
161
Chapter 28. Check if a point lies on or inside a rectangle | Set-2
Yes
Source
https://www.geeksforgeeks.org/check-if-a-point-lies-on-or-inside-a-rectangle-set-2/
162
Chapter 29
This problem is mainly an extension of How to check if given four points form a square
We can solve this problem by using properties of a rectangle. First, we check total unique
end points of segments, if count of these points is not equal to 4 then the line segment
can’t make a rectangle. Then we check distances between all pair of points, there should
163
Chapter 29. Check if four segments form a rectangle
be at most 3 different distances, one for diagonal and two for sides and at the end we will
check the relation among these three distances, for line segments to make a rectangle these
distance should satisfy Pythagorean relation because sides and diagonal of rectangle makes
a right angle triangle. If they satisfy mentioned conditions then we will flag polygon made
by line segment as rectangle otherwise not.
164
Chapter 29. Check if four segments form a rectangle
// calculating distance between all pair of
// end points of line segments
for (auto it1=st.begin(); it1!=st.end(); it1++)
for (auto it2=st.begin(); it2!=st.end(); it2++)
if (*it1 != *it2)
dist.insert(getDis(*it1, *it2));
// if total unique distance are more than 3,
// then line segment can't make a rectangle
if (dist.size() > 3)
return false;
// copying distance into array. Note that set maintains
// sorted order.
int distance[3];
int i = 0;
for (auto it = dist.begin(); it != dist.end(); it++)
distance[i++] = *it;
// If line seqments form a square
if (dist.size() == 2)
return (2*distance[0] == distance[1]);
// distance of sides should satisfy pythagorean
// theorem
return (distance[0] + distance[1] == distance[2]);
}
// Driver code to test above methods
int main()
{
Segment segments[] =
{
{4, 2, 7, 5},
{2, 4, 4, 2},
{2, 4, 5, 7},
{5, 7, 7, 5}
};
(isPossibleRectangle(segments))?cout << "Yes\n":cout << "No\n";
}
Output:
Yes
Improved By : harrypotter0
165
Chapter 29. Check if four segments form a rectangle
Source
https://www.geeksforgeeks.org/check-four-segments-form-rectangle/
166
Chapter 30
Input : 1 1 2 2
Output : Yes
Input : 1 2 3 4
Output : No
Approach 1 :- We will check, if any of the two integers are equal and make sure rest of
two are also equal using few if else conditions.
C++
167
Chapter 30. Check if given four integers (or sides) make rectangle
if (a == b == c == d)
return true;
else if (a == b && c == d)
return true;
else if (a == d && c == b)
return true;
else if (a == c && d == b)
return true;
else
return false;
}
// Driver code
int main()
{
int a, b, c, d;
a = 1, b = 2, c = 3, d = 4;
if (isRectangle(a, b, c, d))
cout << "Yes";
else
cout << "No";
return 0;
}
Java
168
Chapter 30. Check if given four integers (or sides) make rectangle
return true;
else
return false;
}
// Driver code
public static void main(String[] args)
{
int a = 1, b = 2, c = 3, d = 4;
if (isRectangle(a, b, c, d))
System.out.println("Yes");
else
System.out.println("No");
}
}
// This code is contributed by prerna saini.
Python3
169
Chapter 30. Check if given four integers (or sides) make rectangle
# This code is contributed by Ansu Kumari.
C#
170
Chapter 30. Check if given four integers (or sides) make rectangle
Output :
No
C++
Java
171
Chapter 30. Check if given four integers (or sides) make rectangle
int c, int d)
{
if ((a ^ b ^ c ^ d) != 0)
return false;
else
return true;
}
// Driver code
public static void main(String[] args)
{
int a, b, c, d;
a = 3; b = 2; c = 3; d = 2;
if (isRectangle(a, b, c, d))
System.out.println("Yes");
else
System.out.println("No");
}
}
// This code is contributed by
// Smitha Dinesh Semwal
Python3
C#
172
Chapter 30. Check if given four integers (or sides) make rectangle
Output :
Yes
Source
https://www.geeksforgeeks.org/check-given-four-integers-sides-make-rectangle/
173
Chapter 31
Input: angle = 90
Output: YES
Polygons with sides 4 is
possible with angle 90 degrees.
Input: angle = 30
Output: NO
Approach: The Interior angle is defined as the angle between any two adjacent sides of a
regular polygon.
174
Chapter 31. Check if it is possible to create a polygon with a given angle
C++
Java
class GFG
{
// Function to check whether
// it is possible to make a
// regular polygon with a given angle.
static void makePolygon(double a)
{
// N denotes the number of
// sides of polygons possible
double n = 360 / (180 - a);
if (n == (int)n)
System.out.println("YES");
else
System.out.println("NO");
}
175
Chapter 31. Check if it is possible to create a polygon with a given angle
// Driver code
public static void main (String[] args)
{
double a = 90;
// function to print
// the required answer
makePolygon(a);
}
}
// This code is contributed by Bilal
Python3
# Python 3 implementation
# of above approach
# Function to check whether
# it is possible to make a
# regular polygon with a
# given angle.
def makePolygon(a) :
# N denotes the number of sides
# of polygons possible
n = 360 / (180 - a)
if n == int(n) :
print("YES")
else :
print("NO")
# Driver Code
if __name__ == "__main__" :
a = 90
# function calling
makePolygon(a)
# This code is contributed
# by ANKITRAI1
C#
// C# implementation of
176
Chapter 31. Check if it is possible to create a polygon with a given angle
// above approach
using System;
class GFG
{
// Function to check whether
// it is possible to make a
// regular polygon with a
// given angle.
static void makePolygon(double a)
{
// N denotes the number of
// sides of polygons possible
double n = 360 / (180 - a);
if (n == (int)n)
Console.WriteLine("YES");
else
Console.WriteLine("NO");
}
// Driver code
static void Main()
{
double a = 90;
// function to print
// the required answer
makePolygon(a);
}
}
// This code is contributed by mits
PHP
Output:
YES
Source
https://www.geeksforgeeks.org/check-if-it-is-possible-to-create-a-polygon-with-a-given-angle/
177
Chapter 32
Check if right triangle possible from given area and hypotenuse - GeeksforGeeks
Given area and hypotenuse, the aim is to print all sides if right triangle can exist, else print
-1. We need to print all sides in ascending order.
Examples:
Input : 6 5
Output : 3 4 5
Input : 10 6
Output : -1
C++
178
Chapter 32. Check if right triangle possible from given area and hypotenuse
Java
179
Chapter 32. Check if right triangle possible from given area and hypotenuse
Python
180
Chapter 32. Check if right triangle possible from given area and hypotenuse
if D >= 0:
# applying the linear equation
# formula to find both the roots
root1 = (H * H + sqrt(D))/2
root2 = (H * H - sqrt(D))/2
a = sqrt(root1)
b = sqrt(root2)
if b >= a:
print a, b, H
else:
print b, a, H
else:
print "-1"
# Driver code
# Area is 6 and hypotenuse is 5.
findRightAngle(6, 5)
C#
181
Chapter 32. Check if right triangle possible from given area and hypotenuse
PHP
<?php
// PHP program to check existence of
// right triangle.
// Prints three sides of a right trianlge
// from given area and hypotenuse if
// triangle is possible, else prints -1.
function findRightAngle($A, $H)
{
// Descriminant of the equation
$D = pow($H, 4) - 16 * $A * $A;
if ($D >= 0)
{
// applying the linear equation
// formula to find both the roots
$root1 = ($H * $H + sqrt($D)) / 2;
$root2 = ($H * $H - sqrt($D)) / 2;
$a = sqrt($root1);
$b = sqrt($root2);
if ($b >= $a)
echo $a , " ", $b , " " , $H;
else
echo $b , " " , $a , " " , $H;
}
182
Chapter 32. Check if right triangle possible from given area and hypotenuse
else
echo "-1";
}
// Driver code
findRightAngle(6, 5);
// This code is contributed By Anuj_67
?>
Output:
3 4 5
Improved By : vt_m
Source
https://www.geeksforgeeks.org/check-right-angles-possible-given-area-hypotenuse/
183
Chapter 33
Input : a1 = 2, b1 = -3, c1 = 5
a2 = 3, b2 = 4, c2 = -7
a3 = 9, b3 = -5, c3 = 8
Output : Yes
Input : a1 = 2, b1 = -3, c1 = 5
a2 = 3, b2 = 4, c2 = -7
a3 = 9, b3 = -5, c3 = 4
Output : No
Let
a1 x + b1 y + c1 = 0 ………. (1)
a2 x + b2 y + c2 = 0 ………. (2)
a3 x + b3 y + c3 = 0 ………. (3)
Suppose the eqn (i) and (ii) intersets at (x1 , y1 ). Then (x1 , y1 ) will satisfy bothe equations.
Therefore, solving (i) and (ii) using method of cross-multiplication, we get,
(x1 /b1 c2 – b2 c1 ) = (y1 /c1 a2 – c2 a1 ) = (1/a1 b2 – a2 b1 )
184
Chapter 33. Check if three straight lines are concurrent or not
Therefore,
x1 = (b1 c2 – b2 c1 /a1 b2 – a2 b1 ) and
y1 = (c1 a2 – c2 a1 /a1 b2 – a2 b1 ), a1 b2 – a2 b1 != 0
Therefore, the required coodinates of the point of intersection of the lines (i) and (ii) are
(b1 c2 – b2 c1 /a1 b2 – a2 b1 , c1 a2 – c2 a1 /a1 b2 – a2 b1 )
For, three of line to be concurrent, (x1 , y1 ) must satisfy the equation (iii) as well.
So,
a3 x + b3 y + c3 = 0
=> a3 (b1 c2 – b2 c1 /a1 b2 – a2 b1 ) + b3 (c1 a2 – c2 a1 /a1 b2 – a2 b1 ) + c3 = 0
=> a3 (b1 c2 – b2 c1 ) + b3 (c1 a2 – c2 a1 ) + c3 (a1 b2 – a2 b1 ) = 0
So, we only need to check if above condition satisfy or not.
Below is the implemenatation of this approach:
C++
Java
185
Chapter 33. Check if three straight lines are concurrent or not
Python 3
186
Chapter 33. Check if three straight lines are concurrent or not
# Driven Program
a1 = 2
b1 = -3
c1 = 5
a2 = 3
b2 = 4
c2 = -7
a3 = 9
b3 = -5
c3 = 8
if(checkConcurrent(a1, b1, c1, a2, b2, c2,
a3, b3, c3)):
print("Yes")
else:
print("No")
# This code is contributed by Smitha
C#
187
Chapter 33. Check if three straight lines are concurrent or not
Console.WriteLine( "Yes");
else
Console.WriteLine( "No");
}
}
// This code is contributed by anuj_67.
PHP
<?php
// PHP Program to check if three straight
// line are concurrent or not
// Return true if three line are
// concurrent, else false.
function checkConcurrent($a1, $b1, $c1,
$a2, $b2, $c2,
$a3, $b3, $c3)
{
return ($a3 * ($b1 * $c2 - $b2 * $c1) +
$b3 * ($c1 * $a2 - $c2 * $a1) +
$c3 * ($a1 * $b2 - $a2 * $b1) == 0);
}
// Driver Code
$a1 = 2; $b1 = -3; $c1 = 5;
$a2 = 3; $b2 = 4; $c2 = -7;
$a3 = 9; $b3 = -5; $c3 = 8;
if(checkConcurrent($a1, $b1, $c1, $a2, $b2,
$c2, $a3, $b3, $c3))
echo "Yes";
else
echo "No";
// This code is contributed by anuj_67.
?>
Output:
Yes
188
Chapter 33. Check if three straight lines are concurrent or not
Source
https://www.geeksforgeeks.org/check-three-straight-lines-concurrent-not/
189
Chapter 34
Input : C1 = (3, 4)
C2 = (14, 18)
R1 = 5, R2 = 8
Output : Circles do not touch each other.
Input : C1 = (2, 3)
C2 = (15, 28)
R1 = 12, R2 = 10
Output : Circles intersect with each other.
Input : C1 = (-10, 8)
C2 = (14, -24)
R1 = 30, R2 = 10
Input : -10 8
14 -24
30 10
Output : Circle touch each other.
190
Chapter 34. Check if two given circles touch or intersect each other
1. If C1C2 == R1 + R2
Circle A and B are touch to each other.
2. If C1C2 > R1 + R2
Circle A and B are not touch to each other.
3. If C1C2 < R1 + R2
Circle intersects each other.
C++
191
Chapter 34. Check if two given circles touch or intersect each other
Java
Python3
# Python3 program to
192
Chapter 34. Check if two given circles touch or intersect each other
C#
193
Chapter 34. Check if two given circles touch or intersect each other
PHP
<?php
// PHP program to check if two
// circles touch each other or not.
function circle($x1, $y1, $x2,
$y2, $r1, $r2)
{
$distSq = ($x1 - $x2) * ($x1 - $x2) +
($y1 - $y2) * ($y1 - $y2);
$radSumSq = ($r1 + $r2) * ($r1 + $r2);
if ($distSq == $radSumSq)
return 1;
else if ($distSq > $radSumSq)
return -1;
else
194
Chapter 34. Check if two given circles touch or intersect each other
return 0;
}
// Driver code
$x1 = -10; $y1 = 8;
$x2 = 14; $y2 = -24;
$r1 = 30; $r2 = 10;
$t = circle($x1, $y1, $x2,
$y2, $r1, $r2);
if ($t == 1)
echo "Circle touch to each other.";
else if ($t < 0)
echo "Circle not touch to each other.";
else
echo "Circle intersect to each other.";
// This code is contributed by vt_m.
?>
Output :
Improved By : vt_m
Source
https://www.geeksforgeeks.org/check-two-given-circles-touch-intersect/
195
Chapter 35
196
Chapter 35. Check whether a given point lies inside a rectangle or not
#include <bits/stdc++.h>
using namespace std;
/* A utility function to calculate area of
triangle formed by (x1, y1), (x2, y2) and
(x3, y3) */
float area(int x1, int y1, int x2, int y2,
int x3, int y3)
{
return abs((x1 * (y2 - y3) + x2 * (y3 - y1) +
x3 * (y1 - y2)) / 2.0);
}
/* A function to check whether point P(x, y)
lies inside the rectangle formed by A(x1, y1),
B(x2, y2), C(x3, y3) and D(x4, y4) */
bool check(int x1, int y1, int x2, int y2, int x3,
int y3, int x4, int y4, int x, int y)
{
/* Calculate area of rectangle ABCD */
float A = area(x1, y1, x2, y2, x3, y3) +
area(x1, y1, x4, y4, x3, y3);
/* Calculate area of triangle PAB */
float A1 = area(x, y, x1, y1, x2, y2);
/* Calculate area of triangle PBC */
float A2 = area(x, y, x2, y2, x3, y3);
/* Calculate area of triangle PCD */
float A3 = area(x, y, x3, y3, x4, y4);
/* Calculate area of triangle PAD */
float A4 = area(x, y, x1, y1, x4, y4);
/* Check if sum of A1, A2, A3 and A4
is same as A */
return (A == A1 + A2 + A3 + A4);
}
/* Driver program to test above function */
197
Chapter 35. Check whether a given point lies inside a rectangle or not
int main()
{
/* Let us check whether the point P(10, 15)
lies inside the rectangle formed by A(0, 10),
B(10, 0) C(0, -10) D(-10, 0) */
if (check(0, 10, 10, 0, 0, -10, -10, 0, 10, 15))
cout << "yes";
else
cout << "no";
return 0;
}
Java
class GFG
{
/* A utility function to calculate area of
triangle formed by (x1, y1), (x2, y2) and
(x3, y3) */
static float area(int x1, int y1, int x2,
int y2, int x3, int y3)
{
return (float)Math.abs((x1 * (y2 - y3) +
x2 * (y3 - y1) + x3 * (y1 - y2)) / 2.0);
}
/* A function to check whether point P(x, y)
lies inside the rectangle formed by A(x1, y1),
B(x2, y2), C(x3, y3) and D(x4, y4) */
static boolean check(int x1, int y1, int x2, int y2,
int x3, int y3, int x4, int y4, int x, int y)
{
/* Calculate area of rectangle ABCD */
float A = area(x1, y1, x2, y2, x3, y3)+
area(x1, y1, x4, y4, x3, y3);
/* Calculate area of triangle PAB */
float A1 = area(x, y, x1, y1, x2, y2);
/* Calculate area of triangle PBC */
float A2 = area(x, y, x2, y2, x3, y3);
/* Calculate area of triangle PCD */
float A3 = area(x, y, x3, y3, x4, y4);
/* Calculate area of triangle PAD */
float A4 = area(x, y, x1, y1, x4, y4);
198
Chapter 35. Check whether a given point lies inside a rectangle or not
/* Check if sum of A1, A2, A3 and A4
is same as A */
return (A == A1 + A2 + A3 + A4);
}
// Driver code
public static void main (String[] args)
{
/* Let us check whether the point P(10, 15)
lies inside the rectangle formed by A(0, 10),
B(10, 0) C(0, -10) D(-10, 0) */
if (check(0, 10, 10, 0, 0, -10, -10, 0, 10, 15))
System.out.print("yes");
else
System.out.print("no");
}
}
// This code is contributed by Anant Agarwal.
C#
199
Chapter 35. Check whether a given point lies inside a rectangle or not
// Calculate area of rectangle ABCD
float A = area(x1, y1, x2, y2, x3, y3) +
area(x1, y1, x4, y4, x3, y3);
// Calculate area of triangle PAB
float A1 = area(x, y, x1, y1, x2, y2);
// Calculate area of triangle PBC
float A2 = area(x, y, x2, y2, x3, y3);
// Calculate area of triangle PCD
float A3 = area(x, y, x3, y3, x4, y4);
// Calculate area of triangle PAD
float A4 = area(x, y, x1, y1, x4, y4);
// Check if sum of A1, A2, A3
// and A4is same as A
return (A == A1 + A2 + A3 + A4);
}
// Driver code
public static void Main ()
{
// Let us check whether the point
// P(10, 15) lies inside the rectangle
// formed by A(0, 10), B(10, 0),
// C(0, -10), D(-10, 0)
if (check(0, 10, 10, 0, 0, -10, -10, 0, 10, 15))
Console.Write("yes");
else
Console.Write("no");
}
}
// This code is contributed by Nitin Mittal.
PHP
<?php
// PHP program to check whether a
// given point lies inside a
// rectangle or not
// A utility function to
// calculate area of
200
Chapter 35. Check whether a given point lies inside a rectangle or not
201
Chapter 35. Check whether a given point lies inside a rectangle or not
// D(-10, 0)
if (check(0, 10, 10, 0, 0, -10,
-10, 0, 10, 15))
echo "yes";
else
echo "no";
// This code is contributed by vt_m.
?>
Output:
no
Source
https://www.geeksforgeeks.org/check-whether-given-point-lies-inside-rectangle-not/
202
Chapter 36
B(10,30)
/ \
/ \
/ \
/ P \ P'
/ \
A(0,0) ----------- C(20,0)
Solution:
Let the coordinates of three corners be (x1, y1), (x2, y2) and (x3, y3). And coordinates of
the given point P be (x, y)
1) Calculate area of the given triangle, i.e., area of the triangle ABC in the above diagram.
Area A = [ x1(y2 – y3) + x2(y3 – y1) + x3(y1-y2)]/2
2) Calculate area of the triangle PAB. We can use the same formula for this. Let this area
be A1.
3) Calculate area of the triangle PBC. Let this area be A2.
4) Calculate area of the triangle PAC. Let this area be A3.
5) If P lies inside the triangle, then A1 + A2 + A3 must be equal to A.
C++
203
Chapter 36. Check whether a given point lies inside a triangle or not
#include <bits/stdc++.h>
using namespace std;
/* A utility function to calculate area of triangle formed by (x1, y1),
(x2, y2) and (x3, y3) */
float area(int x1, int y1, int x2, int y2, int x3, int y3)
{
return abs((x1*(y2-y3) + x2*(y3-y1)+ x3*(y1-y2))/2.0);
}
/* A function to check whether point P(x, y) lies inside the triangle formed
by A(x1, y1), B(x2, y2) and C(x3, y3) */
bool isInside(int x1, int y1, int x2, int y2, int x3, int y3, int x, int y)
{
/* Calculate area of triangle ABC */
float A = area (x1, y1, x2, y2, x3, y3);
/* Calculate area of triangle PBC */
float A1 = area (x, y, x2, y2, x3, y3);
/* Calculate area of triangle PAC */
float A2 = area (x1, y1, x, y, x3, y3);
/* Calculate area of triangle PAB */
float A3 = area (x1, y1, x2, y2, x, y);
/* Check if sum of A1, A2 and A3 is same as A */
return (A == A1 + A2 + A3);
}
/* Driver program to test above function */
int main()
{
/* Let us check whether the point P(10, 15) lies inside the triangle
formed by A(0, 0), B(20, 0) and C(10, 30) */
if (isInside(0, 0, 20, 0, 10, 30, 10, 15))
printf ("Inside");
else
printf ("Not Inside");
return 0;
}
Java
204
Chapter 36. Check whether a given point lies inside a triangle or not
class GFG {
/* A utility function to calculate area of triangle
formed by (x1, y1) (x2, y2) and (x3, y3) */
static double area(int x1, int y1, int x2, int y2,
int x3, int y3)
{
return Math.abs((x1*(y2-y3) + x2*(y3-y1)+
x3*(y1-y2))/2.0);
}
/* A function to check whether point P(x, y) lies
inside the triangle formed by A(x1, y1),
B(x2, y2) and C(x3, y3) */
static boolean isInside(int x1, int y1, int x2,
int y2, int x3, int y3, int x, int y)
{
/* Calculate area of triangle ABC */
double A = area (x1, y1, x2, y2, x3, y3);
/* Calculate area of triangle PBC */
double A1 = area (x, y, x2, y2, x3, y3);
/* Calculate area of triangle PAC */
double A2 = area (x1, y1, x, y, x3, y3);
/* Calculate area of triangle PAB */
double A3 = area (x1, y1, x2, y2, x, y);
/* Check if sum of A1, A2 and A3 is same as A */
return (A == A1 + A2 + A3);
}
/* Driver program to test above function */
public static void main(String[] args)
{
/* Let us check whether the point P(10, 15)
lies inside the triangle formed by
A(0, 0), B(20, 0) and C(10, 30) */
if (isInside(0, 0, 20, 0, 10, 30, 10, 15))
System.out.println("Inside");
else
System.out.println("Not Inside");
}
}
205
Chapter 36. Check whether a given point lies inside a triangle or not
Python
206
Chapter 36. Check whether a given point lies inside a triangle or not
C#
207
Chapter 36. Check whether a given point lies inside a triangle or not
Console.WriteLine("Inside");
else
Console.WriteLine("Not Inside");
}
}
// This code is contributed by vt_m.
PHP
<?php
/* A utility function to calculate
area of triangle formed by (x1, y1),
(x2, y2) and (x3, y3) */
function area($x1, $y1, $x2,
$y2, $x3, $y3)
{
return abs(($x1 * ($y2 - $y3) +
$x2 * ($y3 - $y1) +
$x3 * ($y1 - $y2)) / 2.0);
}
/* A function to check whether
P(x, y) lies inside the
triangle formed by A(x1, y1),
B(x2, y2) and C(x3, y3) */
function isInside($x1, $y1, $x2, $y2,
$x3, $y3, $x, $y)
{
/* Calculate area of triangle ABC */
$A = area ($x1, $y1, $x2, $y2, $x3, $y3);
/* Calculate area of triangle PBC */
$A1 = area ($x, $y, $x2, $y2, $x3, $y3);
/* Calculate area of triangle PAC */
$A2 = area ($x1, $y1, $x, $y, $x3, $y3);
/* Calculate area of triangle PAB */
$A3 = area ($x1, $y1, $x2, $y2, $x, $y);
/* Check if sum of A1, A2
and A3 is same as A */
return ($A == $A1 + $A2 + $A3);
}
208
Chapter 36. Check whether a given point lies inside a triangle or not
Ouptut:
Inside
Exercise: Given coordinates of four corners of a rectangle, and a point P. Write a function
to check whether P lies inside the given rectangle or not.
Improved By : vt_m
Source
https://www.geeksforgeeks.org/check-whether-a-given-point-lies-inside-a-triangle-or-not/
209
Chapter 37
Check whether a given point lies on or inside the rectangle | Set 3 - GeeksforGeeks
Given two numbers a and b where b < a form a rectangle with points (0, b), (b, 0), (a-b,
b), (b, a-b). Given a point (x, y), the task is to check whether this point lies inside or on
the rectangle or not.
Examples:
Input: a = 7, b = 2, x = 5, y = 2;
Output: Given point does not lie on the rectangle
Input: a = 7, b = 2, x = 4, y = 5;
Output: Given point lies inside the rectangle
1. The right sideline ( x-y-b = 0 ) must give the value less than or equals to zero.
2. The left sideline ( x-y+a = 0 ) must give the value greater than or equals to one.
3. The upper sideline ( x+y-2*a+b = 0 ) must give the value less than or equals to
zero.
4. The lower sideline ( x+y-b = 0 ) must give the value greater than or equals to one.
C++
210
Chapter 37. Check whether a given point lies on or inside the rectangle | Set 3
Java
// Java program to Check whether
// a given point lies inside or
// on the rectangle or not
class GFG
{
// function to Check whether
// a given point lies inside
// or on the rectangle or not
static boolean LiesInsieRectangle(int a, int b,
int x, int y)
{
if (x – y – b <= 0 && x - y + b >= 0 &&
x + y – 2 * a + b <= 0 && x + y - b >= 0)
return true;
return false;
}
// Driver code
public static void main(String[] args)
211
Chapter 37. Check whether a given point lies on or inside the rectangle | Set 3
{
int a = 7, b = 2, x = 4, y = 5;
if (LiesInsieRectangle(a, b, x, y))
System.out.println(“Given point lies ” +
“inside the rectangle”);
else
System.out.println(“Given point does not ” +
“lie on the rectangle”);
}
}
// This code is contributed
// by ChitraNayal
Python3
C#
212
Chapter 37. Check whether a given point lies on or inside the rectangle | Set 3
<?php
// PHP program to Check whether
// a given point lies inside
// or on the rectangle or not
// function to Check whether
// a given point lies inside
// or on the rectangle or not
function LiesInsieRectangle($a, $b,
$x, $y)
{
if ($x - $y - $b <= 0 &&
213
Chapter 37. Check whether a given point lies on or inside the rectangle | Set 3
Output:
Source
https://www.geeksforgeeks.org/check-whether-a-given-point-lies-on-or-inside-the-rectangle-set-3/
214
Chapter 38
Input : Radius = 8
StartAngle = 0
Percentage = 12
x = 3 y = 4
Output : Point (3, 4) exists in the circle
sector
Input : Radius = 12
Startangle = 45
Percentage = 25
x = 3 y = 4
Output : Point (3, 4) does not exist in
the circle sector
215
Chapter 38. Check whether a point exists in circle sector or not.
Source:wikibooks.org
In this image starting angle is 0 degree, radius r and suppose that percentage of colored
area is 12% then we calculate Ending Angle as 360/percentage + starting angle.
To find whether a point (x, y) exists in a circle sector (centered at origin) or not we find
polar coordinates of that point and then go through the following steps:
C++
216
Chapter 38. Check whether a point exists in circle sector or not.
// or not
if (Angle>=startAngle && Angle<=endAngle && polarradius<radius)
printf("Point (%d, %d) exist in the circle sector\n", x, y);
else
printf("Point (%d, %d) does not exist in the circle sector\n",
x, y);
}
// Driver code
int main()
{
int radius = 8, x = 3, y = 4;
float percent = 12, startAngle = 0;
checkPoint(radius, x, y, percent, startAngle);
return 0;
}
Java
217
Chapter 38. Check whether a point exists in circle sector or not.
// Driver Program to test above function
public static void main(String arg[])
{
int radius = 8, x = 3, y = 4;
float percent = 12, startAngle = 0;
checkPoint(radius, x, y, percent, startAngle);
}
}
// This code is contributed
// by Anant Agarwal.
Python3
218
Chapter 38. Check whether a point exists in circle sector or not.
C#
Output :
219
Chapter 38. Check whether a point exists in circle sector or not.
Source
https://www.geeksforgeeks.org/check-whether-point-exists-circle-sector-not/
220
Chapter 39
Approach:
Whether a point lies inside a sphere or not, depends upon its distance from the centre.
A point (x, y, z) is inside the sphere with center (cx, cy, cz) and radius r if
A point (x, y, z) lies on the sphere with center (cx, cy, cz) and radius r if
221
Chapter 39. Check whether a point lies inside a sphere or not
A point (x, y, z) is outside the sphere with center (cx, cy, cz) and radius r if
C++
222
Chapter 39. Check whether a point lies inside a sphere or not
Java
223
Chapter 39. Check whether a point lies inside a sphere or not
Python
224
Chapter 39. Check whether a point lies inside a sphere or not
C#
// C# code to illustrate
// above approach
using System;
class GFG
{
// function to calculate
// the distance between
// centre and the point
public static int check(int cx, int cy,
int cz, int x,
int y, int z)
{
int x1 = (int)Math.Pow((x - cx), 2);
int y1 = (int)Math.Pow((y - cy), 2);
int z1 = (int)Math.Pow((z - cz), 2);
// distance between the
// centre and given point
return (x1 + y1 + z1);
}
// Driver Code
public static void Main()
{
// coordinates of centre
int cx = 1, cy = 2, cz = 3;
int r = 5; // radius of the sphere
// coordinates of point
int x = 4, y = 5, z = 2;
int ans = check(cx, cy, cz,
x, y, z);
// distance btw centre
// and point is less
// than radius
if (ans < (r * r))
Console.WriteLine("Point is inside" +
" the sphere");
// distance btw centre
// and point is
225
Chapter 39. Check whether a point lies inside a sphere or not
PHP
<?php
// function to calculate
// the distance between
// centre and the point
function check($cx, $cy, $cz,
$x, $y, $z)
{
$x1 = pow(($x - $cx), 2);
$y1 = pow(($y - $cy), 2);
$z1 = pow(($z - $cz), 2);
// distance between the
// centre and given point
return ($x1 + $y1 + $z1);
}
// Driver Code
// coordinates of centre
$cx = 1;
$cy = 2;
$cz = 3;
$r = 5; // radius of the sphere
$x = 4;
$y = 5;
$z = 2; // coordinates of point
$ans = check($cx, $cy, $cz,
$x, $y, $z);
226
Chapter 39. Check whether a point lies inside a sphere or not
// distance btw centre and
// point is less than radius
if ($ans < ($r * $r))
echo "Point is inside " .
"the sphere";
// distance btw centre and
// point is equal to radius
else if ($ans == ($r * $r))
echo "Point lies on the sphere";
// distance btw center and point
// is greater than radius
else
echo "Point is outside " .
"the sphere";
// This code is contributed
// by shiv_bhakt
?>
Output:
Time Complexity:O(1)
Improved By : vt_m, shiv_bhakt
Source
https://www.geeksforgeeks.org/check-whether-a-point-lies-inside-a-sphere-or-not/
227
Chapter 40
A parallelogram has four sides. Two opposite sides are parallel and are of same lengths.
Examples:
Problems for checking square and rectangle can be read from Square checking and Rectangle
checking but in this problem, we need to check for the parallelogram. The main properties
of the parallelogram are that opposite sides of parallelogram are parallel and of equal length
228
Chapter 40. Check whether four points make a parallelogram
and diagonals of parallelogram bisect each other. We use the second property to solve this
problem. As there are four points, we can get total 6 midpoints by considering each pair.
Now for four points to make a parallelogram, 2 of the midpoints should be equal and rest
of them should be different.
In below code, we have created a map, which stores pairs corresponding to each midpoint.
After calculating all midpoints, we have iterated over the map and check the occurrence of
each midpoint, If exactly one midpoint occurred twice and other have occurred once, then
given four points make a parallelogram otherwise not.
229
Chapter 40. Check whether four points make a parallelogram
230
Chapter 40. Check whether four points make a parallelogram
Output:
Source
https://www.geeksforgeeks.org/check-whether-four-points-make-parallelogram/
231
Chapter 41
Check whether given circle resides in boundary maintained by two other circles - Geeks-
forGeeks
Given outer circle radius R and inner circle radius r, making circles from same center and
forming boundary between them. Now, given X,Y co-ordinates which denotes center of new
circle to be formed with radius rad, your task is to check whether the circle with co-ordinate
X,Y as center can fit in the boundary of circles formed or not.
Examples:
Input : R = 8, r = 4
x = 5, y = 3, rad = 1
Output : Fits
Input : R = 8, r = 4
x = 5, y = 3, rad = 3.
Output : Doesn't Fit
232
Chapter 41. Check whether given circle resides in boundary maintained by two other circles
1 – Doesn’t fits
2 – Fits
The idea is to calculate the distance between the center (0, 0) and the co-ordinates of the
circle to be checked. If distance + radius (of the circle to be checked) is less than or equal
to Outer Radius and distance – radius (of the circle to be checked) is greater than or equal
to Radius of Outer circle – Radius Inner circle
It fits.
Here is the implementation :
233
Chapter 41. Check whether given circle resides in boundary maintained by two other circles
C++
Java
234
Chapter 41. Check whether given circle resides in boundary maintained by two other circles
// boundary or not
static void fitOrNotFit(int R, int r, int x, int y,
int rad)
{
// Distance from the center
double val = Math.sqrt(Math.pow(x, 2) +
Math.pow(y, 2));
// Checking the corners of circle
if (val + rad <= R && val - rad >= R - r)
System.out.println("Fits");
else
System.out.println("Doesn't Fit");
}
// driver program
public static void main (String[] args)
{
// Radius of outer circle and inner circle
// respectively
int R = 8, r = 4;
// Co-ordinates and radius of the circle
// to be checked
int x = 5, y = 3, rad = 3;
fitOrNotFit(R, r, x, y, rad);
}
}
/* This Code is contributed by Kriti Shukla */
Python3
235
Chapter 41. Check whether given circle resides in boundary maintained by two other circles
# Checking the corners of circle
if (val + rad <= R and val - rad >= R - r) :
print("Fits\n")
else:
print("Doesn't Fit")
# driver program
# Radius of outer circle and inner circle
# respectively
R = 8
r = 4
# Co-ordinates and radius of the circle
# to be checked
x = 5
y = 3
rad = 3
fitOrNotFit(R, r, x, y, rad)
# This code is contributed by
# Smitha Dinesh Semwal
C#
236
Chapter 41. Check whether given circle resides in boundary maintained by two other circles
Console.WriteLine("Doesn't Fit");
}
// Driver program
public static void Main ()
{
// Radius of outer circle and inner circle
// respectively
int R = 8, r = 4;
// Co-ordinates and radius of the circle
// to be checked
int x = 5, y = 3, rad = 3;
fitOrNotFit(R, r, x, y, rad);
}
}
// This Code is contributed by Anant Agarwal.
PHP
<?php
// PHP 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
function fitOrNotFit($R, $r, $x, $y,
$rad)
{
// Distance from the center
$val = sqrt(pow($x, 2) + pow($y, 2));
// Checking the corners of circle
if ($val + $rad <= $R && $val -
$rad >= $R - $r)
echo"Fits\n";
else
echo "Doesn't Fit\n";
}
// Driver Code
// Radius of outer circle and
// inner circle respectively
237
Chapter 41. Check whether given circle resides in boundary maintained by two other circles
$R = 8; $r = 4;
// Co-ordinates and radius of
// the circle to be checked
$x = 5; $y = 3; $rad = 3;
fitOrNotFit($R, $r, $x, $y, $rad);
// This Code is contributed by vt_m.
?>
Output:
Doesn't Fit
Improved By : vt_m
Source
https://www.geeksforgeeks.org/check-whether-given-circle-reside-boundary-maintained-outer-circle-inner-circle/
238
Chapter 42
Input : a = 7, b = 10, c = 5
Output : Valid
Input : a = 1 b = 10 c = 12
Output : Invalid
Approach: A triangle is valid if sum of its two sides is greater than the third side. If three
sides are a, b and c, then three conditions should be met.
1.a + b > c
2.a + c > b
3.b + c > a
239
Chapter 42. Check whether triangle is valid or not if sides are given
C++
240
Chapter 42. Check whether triangle is valid or not if sides are given
Java
Python3
241
Chapter 42. Check whether triangle is valid or not if sides are given
return False
else:
return True
# driver code
a = 7
b = 10
c = 5
if checkValidity(a, b, c):
print("Valid")
else:
print("Invalid")
C#
// C# program to check
// validity of any triangle
using System;
class GFG {
// Function to calculate for validity
public static int checkValidity(int a, int b,
int c)
{
// check condition
if (a + b <= c || a + c <= b ||
b + c <= a)
return 0;
else
return 1;
}
// Driver code
public static void Main()
{
int a = 7, b = 10, c = 5;
// function calling and print output
if ((checkValidity(a, b, c)) == 1)
Console.Write("Valid");
else
Console.Write("Invalid");
}
}
242
Chapter 42. Check whether triangle is valid or not if sides are given
PHP
<?php
// PHP program to check if three
// sides form a triangle or not
// function to check if three sider
// form a triangle or not
function checkValidity($a, $b, $c)
{
// check condition
if ($a + $b <= $c ||
$a + $c <= $b ||
$b + $c <= $a)
return false;
else
return true;
}
// Driver Code
$a = 7;
$b = 10;
$c = 5;
if (checkValidity($a, $b, $c))
echo "Valid";
else
echo "Invalid";
// This code is contributed by nitin mittal.
?>
Output :
Valid
Source
https://www.geeksforgeeks.org/check-whether-triangle-valid-not-sides-given/
243
Chapter 43
Input : r = 5.
Output : 12
Below are lattice points on a circle with
radius 5 and origin as (0, 0).
(0,5), (0,-5), (5,0), (-5,0),
(3,4), (-3,4), (-3,-4), (3,-4),
(4,3), (-4,3), (-4,-3), (4,-3).
are 12 lattice point.
To find lattice points, we basically need to find values of (x, y) which satisfy the equation
x2 + y2 = r2 .
For any value of (x, y) that satisfies the above equation we actually have total 4 different
combination which that satisfy the equation. For example if r = 5 and (3, 4) is a pair which
satisfies the equation, there are actually 4 combinations (3, 4) , (-3,4) , (-3,-4) , (3,-4). There
is an exception though, in case of (0, r) or (r, 0) there are actually 2 points as there is no
negative 0.
244
Chapter 43. Circle and Lattice Points
CPP
Java
245
Chapter 43. Circle and Lattice Points
Python3
246
Chapter 43. Circle and Lattice Points
import math
# Function to count Lattice
# podefs on a circle
def countLattice(r):
if (r <= 0):
return 0
# Initialize result as 4 for (r, 0), (-r. 0),
# (0, r) and (0, -r)
result = 4
# Check every value that can be potential x
for x in range(1, r):
# Find a potential y
ySquare = r*r - x*x
y = int(math.sqrt(ySquare))
# checking whether square root is an defeger
# or not. Count increments by 4 for four
# different quadrant values
if (y*y == ySquare):
result += 4
return result
# Driver program
r = 5
print(countLattice(r))
# This code is contributed by
# Smitha Dinesh Semwal
C#
247
Chapter 43. Circle and Lattice Points
{
if (r <= 0)
return 0;
// Initialize result as 4
// for (r, 0), (-r. 0),
// (0, r) and (0, -r)
int result = 4;
// Check every value that
// can be potential x
for (int x = 1; x < r; x++)
{
// Find a potential y
int ySquare = r*r - x*x;
int y = (int)Math.Sqrt(ySquare);
// checking whether square root
// is an integer or not. Count
// increments by 4 for four
// different quadrant values
if (y*y == ySquare)
result += 4;
}
return result;
}
// Driver code
public static void Main()
{
int r = 5;
Console.Write(countLattice(r));
}
}
// This code is contributed by nitin mittal.
PHP
<?php
// PHP program to find countLattice
// points on a circle
// Function to count Lattice
// points on a circle
248
Chapter 43. Circle and Lattice Points
function countLattice($r)
{
if ($r <= 0)
return 0;
// Initialize result as 4
// for (r, 0), (-r. 0),
// (0, r) and (0, -r)
$result = 4;
// Check every value that
// can be potential x
for ($x = 1; $x < $r; $x++)
{
// Find a potential y
$ySquare = $r * $r - $x * $x;
$y = ceil(sqrt($ySquare));
// checking whether square
// root is an integer
// or not. Count increments
// by 4 for four different
// quadrant values
if ($y * $y == $ySquare)
$result += 4;
}
return $result;
}
// Driver Code
$r = 5;
echo countLattice($r);
// This code is contributed by nitin mittal
?>
Output:
12
Reference:
http://mathworld.wolfram.com/CircleLatticePoints.html
Improved By : nitin mittal
249
Chapter 43. Circle and Lattice Points
Source
https://www.geeksforgeeks.org/circle-lattice-points/
250
Chapter 44
Classify a triangle
We can solve this problem by first calculating the side length and then classifying on com-
paring of side lengths. Classification by sides is simple, if all sides are equal, triangle will
be equilateral, if any two sides are equal triangle will be Isosceles otherwise it will be
Scalene.
Now angle can be classified by Pythagoras theorem, if sum of square of two sides is equal to
square of third side, triangle will be right angle, if less triangle will be acute angle else
it will be obtuse angle triangle.
Below is written simple code for classification of triangle :
251
Chapter 44. Classify a triangle
};
// Utility method to return square of x
int square(int x)
{
return x * x;
}
// Utility method to sort a, b, c; after this
// method a <= b <= c
void order(int &a, int &b, int &c)
{
int copy[3];
copy[0] = a;
copy[1] = b;
copy[2] = c;
sort(copy, copy + 3);
a = copy[0];
b = copy[1];
c = copy[2];
}
// Utility method to return Square of distance
// between two points
int euclidDistSquare(point p1, point p2)
{
return square(p1.x - p2.x) + square(p1.y - p2.y);
}
// Method to classify side
string getSideClassification(int a, int b, int c)
{
// if all sides are equal
if (a == b && b == c)
return "Equilateral";
// if any two sides are equal
else if (a == b || b == c)
return "Isosceles";
else
return "Scalene";
}
// Method to classify angle
string getAngleClassification(int a, int b, int c)
{
// If addition of sum of square of two side
252
Chapter 44. Classify a triangle
Output:
253
Chapter 44. Classify a triangle
Source
https://www.geeksforgeeks.org/classify-a-triangle/
254
Chapter 45
The Brute force solution is O(n^2), compute the distance between each pair and return the
smallest. We can calculate the smallest distance in O(nLogn) time using Divide and Conquer
strategy. In this post, a O(n x (Logn)^2) approach is discussed. We will be discussing a
O(nLogn) approach in a separate post.
Algorithm
Following are the detailed steps of a O(n (Logn)^2) algortihm.
Input: An array of n points P[]
Output: The smallest distance between two points in the given array.
As a pre-processing step, input array is sorted according to x coordinates.
1) Find the middle point in the sorted array, we can take P[n/2] as middle point.
2) Divide the given array in two halves. The first subarray contains points from P[0] to
P[n/2]. The second subarray contains points from P[n/2+1] to P[n-1].
3) Recursively find the smallest distances in both subarrays. Let the distances be dl and
dr. Find the minimum of dl and dr. Let the minimum be d.
255
Chapter 45. Closest Pair of Points using Divide and Conquer algorithm
4) From above 3 steps, we have an upper bound d of minimum distance. Now we need to
consider the pairs such that one point in pair is from left half and other is from right half.
Consider the vertical line passing through passing through P[n/2] and find all points whose
x coordinate is closer than d to the middle vertical line. Build an array strip[] of all such
points.
256
Chapter 45. Closest Pair of Points using Divide and Conquer algorithm
5) Sort the array strip[] according to y coordinates. This step is O(nLogn). It can be
optimized to O(n) by recursively sorting and merging.
6) Find the smallest distance in strip[]. This is tricky. From first look, it seems to be a
O(n^2) step, but it is actually O(n). It can be proved geometrically that for every point in
strip, we only need to check at most 7 points after it (note that strip is sorted according to
Y coordinate). See thisfor more analysis.
7) Finally return the minimum of d and distance calculated in above step (step 6)
Implementation
Following is C/C++ implementation of the above algorithm.
// A divide and conquer program in C/C++ to find the smallest distance from a
// given set of points.
#include <stdio.h>
257
Chapter 45. Closest Pair of Points using Divide and Conquer algorithm
#include <float.h>
#include <stdlib.h>
#include <math.h>
// A structure to represent a Point in 2D plane
struct Point
{
int x, y;
};
/* Following two functions are needed for library function qsort().
Refer: http://www.cplusplus.com/reference/clibrary/cstdlib/qsort/ */
// Needed to sort array of points according to X coordinate
int compareX(const void* a, const void* b)
{
Point *p1 = (Point *)a, *p2 = (Point *)b;
return (p1->x - p2->x);
}
// Needed to sort array of points according to Y coordinate
int compareY(const void* a, const void* b)
{
Point *p1 = (Point *)a, *p2 = (Point *)b;
return (p1->y - p2->y);
}
// A utility function to find the distance between two points
float dist(Point p1, Point p2)
{
return sqrt( (p1.x - p2.x)*(p1.x - p2.x) +
(p1.y - p2.y)*(p1.y - p2.y)
);
}
// A Brute Force method to return the smallest distance between two points
// in P[] of size n
float bruteForce(Point P[], int n)
{
float min = FLT_MAX;
for (int i = 0; i < n; ++i)
for (int j = i+1; j < n; ++j)
if (dist(P[i], P[j]) < min)
min = dist(P[i], P[j]);
return min;
}
// A utility function to find minimum of two float values
float min(float x, float y)
258
Chapter 45. Closest Pair of Points using Divide and Conquer algorithm
{
return (x < y)? x : y;
}
// A utility function to find the distance beween the closest points of
// strip of given size. All points in strip[] are sorted accordint to
// y coordinate. They all have an upper bound on minimum distance as d.
// Note that this method seems to be a O(n^2) method, but it's a O(n)
// method as the inner loop runs at most 6 times
float stripClosest(Point strip[], int size, float d)
{
float min = d; // Initialize the minimum distance as d
qsort(strip, size, sizeof(Point), compareY);
// Pick all points one by one and try the next points till the difference
// between y coordinates is smaller than d.
// This is a proven fact that this loop runs at most 6 times
for (int i = 0; i < size; ++i)
for (int j = i+1; j < size && (strip[j].y - strip[i].y) < min; ++j)
if (dist(strip[i],strip[j]) < min)
min = dist(strip[i], strip[j]);
return min;
}
// A recursive function to find the smallest distance. The array P contains
// all points sorted according to x coordinate
float closestUtil(Point P[], int n)
{
// If there are 2 or 3 points, then use brute force
if (n <= 3)
return bruteForce(P, n);
// Find the middle point
int mid = n/2;
Point midPoint = P[mid];
// Consider the vertical line passing through the middle point
// calculate the smallest distance dl on left of middle point and
// dr on right side
float dl = closestUtil(P, mid);
float dr = closestUtil(P + mid, n-mid);
// Find the smaller of two distances
float d = min(dl, dr);
259
Chapter 45. Closest Pair of Points using Divide and Conquer algorithm
// Build an array strip[] that contains points close (closer than d)
// to the line passing through the middle point
Point strip[n];
int j = 0;
for (int i = 0; i < n; i++)
if (abs(P[i].x - midPoint.x) < d)
strip[j] = P[i], j++;
// Find the closest points in strip. Return the minimum of d and closest
// distance is strip[]
return min(d, stripClosest(strip, j, d) );
}
// The main functin that finds the smallest distance
// This method mainly uses closestUtil()
float closest(Point P[], int n)
{
qsort(P, n, sizeof(Point), compareX);
// Use recursive function closestUtil() to find the smallest distance
return closestUtil(P, n);
}
// Driver program to test above functions
int main()
{
Point P[] = {{2, 3}, {12, 30}, {40, 50}, {5, 1}, {12, 10}, {3, 4}};
int n = sizeof(P) / sizeof(P[0]);
printf("The smallest distance is %f ", closest(P, n));
return 0;
}
Output:
Time Complexity Let Time complexity of above algorithm be T(n). Let us assume that
we use a O(nLogn) sorting algorithm. The above algorithm divides all points in two sets
and recursively calls for two sets. After dividing, it finds the strip in O(n) time, sorts the
strip in O(nLogn) time and finally finds the closest points in strip in O(n) time. So T(n)
can expressed as follows
T(n) = 2T(n/2) + O(n) + O(nLogn) + O(n)
T(n) = 2T(n/2) + O(nLogn)
T(n) = T(n x Logn x Logn)
Notes
1) Time complexity can be improved to O(nLogn) by optimizing step 5 of the above algo-
rithm. We will soon be discussing the optimized solution in a separate post.
260
Chapter 45. Closest Pair of Points using Divide and Conquer algorithm
2) The code finds smallest distance. It can be easily modified to find the points with small-
est distance.
3) The code uses quick sort which can be O(n^2) in worst case. To have the upper bound
as O(n (Logn)^2), a O(nLogn) sorting algorithm like merge sort or heap sort can be used
References:
http://www.cs.umd.edu/class/fall2013/cmsc451/Lects/lect10.pdf
http://www.youtube.com/watch?v=vS4Zn1a9KUc
http://www.youtube.com/watch?v=T3T7T8Ym20M
http://en.wikipedia.org/wiki/Closest_pair_of_points_problem
Source
https://www.geeksforgeeks.org/closest-pair-of-points-using-divide-and-conquer-algorithm/
261
Chapter 46
We have discussed a divide and conquer solution for this problem. The time complexity of
the implementation provided in the previous post is O(n (Logn)^2). In this post, we discuss
an implementation with time complexity as O(nLogn).
Following is a recap of the algorithm discussed in the previous post.
1) We sort all points according to x coordinates.
2) Divide all points in two halves.
3) Recursively find the smallest distances in both subarrays.
4) Take the minimum of two smallest distances. Let the minimum be d.
5) Create an array strip[] that stores all points which are at most d distance away from the
middle line dividing the two sets.
6) Find the smallest distance in strip[].
7) Return the minimum of d and the smallest distance calculated in above step 6.
The great thing about the above approach is, if the array strip[] is sorted according to y
coordinate, then we can find the smallest distance in strip[] in O(n) time. In the implemen-
tation discussed in previous post, strip[] was explicitly sorted in every recursive call that
made the time complexity O(n (Logn)^2), assuming that the sorting step takes O(nLogn)
262
Chapter 46. Closest Pair of Points | O(nlogn) Implementation
time.
In this post, we discuss an implementation where the time complexity is O(nLogn). The
idea is to presort all points according to y coordinates. Let the sorted array be Py[]. When
we make recursive calls, we need to divide points of Py[] also according to the vertical line.
We can do that by simply processing every point and comparing its x coordinate with x
coordinate of middle line.
Following is C++ implementation of O(nLogn) approach.
// A divide and conquer program in C++ to find the smallest distance from a
// given set of points.
#include <iostream>
#include <float.h>
#include <stdlib.h>
#include <math.h>
using namespace std;
// A structure to represent a Point in 2D plane
struct Point
{
int x, y;
};
/* Following two functions are needed for library function qsort().
Refer: http://www.cplusplus.com/reference/clibrary/cstdlib/qsort/ */
// Needed to sort array of points according to X coordinate
int compareX(const void* a, const void* b)
{
Point *p1 = (Point *)a, *p2 = (Point *)b;
return (p1->x - p2->x);
}
// Needed to sort array of points according to Y coordinate
int compareY(const void* a, const void* b)
{
Point *p1 = (Point *)a, *p2 = (Point *)b;
return (p1->y - p2->y);
}
// A utility function to find the distance between two points
float dist(Point p1, Point p2)
{
return sqrt( (p1.x - p2.x)*(p1.x - p2.x) +
(p1.y - p2.y)*(p1.y - p2.y)
);
}
263
Chapter 46. Closest Pair of Points | O(nlogn) Implementation
// A Brute Force method to return the smallest distance between two points
// in P[] of size n
float bruteForce(Point P[], int n)
{
float min = FLT_MAX;
for (int i = 0; i < n; ++i)
for (int j = i+1; j < n; ++j)
if (dist(P[i], P[j]) < min)
min = dist(P[i], P[j]);
return min;
}
// A utility function to find minimum of two float values
float min(float x, float y)
{
return (x < y)? x : y;
}
// A utility function to find the distance beween the closest points of
// strip of given size. All points in strip[] are sorted accordint to
// y coordinate. They all have an upper bound on minimum distance as d.
// Note that this method seems to be a O(n^2) method, but it's a O(n)
// method as the inner loop runs at most 6 times
float stripClosest(Point strip[], int size, float d)
{
float min = d; // Initialize the minimum distance as d
// Pick all points one by one and try the next points till the difference
// between y coordinates is smaller than d.
// This is a proven fact that this loop runs at most 6 times
for (int i = 0; i < size; ++i)
for (int j = i+1; j < size && (strip[j].y - strip[i].y) < min; ++j)
if (dist(strip[i],strip[j]) < min)
min = dist(strip[i], strip[j]);
return min;
}
// A recursive function to find the smallest distance. The array Px contains
// all points sorted according to x coordinates and Py contains all points
// sorted according to y coordinates
float closestUtil(Point Px[], Point Py[], int n)
{
// If there are 2 or 3 points, then use brute force
if (n <= 3)
return bruteForce(Px, n);
264
Chapter 46. Closest Pair of Points | O(nlogn) Implementation
265
Chapter 46. Closest Pair of Points | O(nlogn) Implementation
Px[i] = P[i];
Py[i] = P[i];
}
qsort(Px, n, sizeof(Point), compareX);
qsort(Py, n, sizeof(Point), compareY);
// Use recursive function closestUtil() to find the smallest distance
return closestUtil(Px, Py, n);
}
// Driver program to test above functions
int main()
{
Point P[] = {{2, 3}, {12, 30}, {40, 50}, {5, 1}, {12, 10}, {3, 4}};
int n = sizeof(P) / sizeof(P[0]);
cout << "The smallest distance is " << closest(P, n);
return 0;
}
Output:
Time Complexity:Let Time complexity of above algorithm be T(n). Let us assume that
we use a O(nLogn) sorting algorithm. The above algorithm divides all points in two sets
and recursively calls for two sets. After dividing, it finds the strip in O(n) time. Also, it
takes O(n) time to divide the Py array around the mid vertical line. Finally finds the closest
points in strip in O(n) time. So T(n) can expressed as follows
T(n) = 2T(n/2) + O(n) + O(n) + O(n)
T(n) = 2T(n/2) + O(n)
T(n) = T(nLogn)
References:
http://www.cs.umd.edu/class/fall2013/cmsc451/Lects/lect10.pdf
http://www.youtube.com/watch?v=vS4Zn1a9KUc
http://www.youtube.com/watch?v=T3T7T8Ym20M
http://en.wikipedia.org/wiki/Closest_pair_of_points_problem
Source
https://www.geeksforgeeks.org/closest-pair-of-points-onlogn-implementation/
266
Chapter 47
Input is an array of points specified by their x and y coordinates. The output is the convex
hull of this set of points.
Examples:
Input : points[] = {(0, 0), (0, 4), (-4, 0), (5, 0),
(0, -6), (1, 0)};
Output : (-4, 0), (5, 0), (0, -6), (0, 4)
Pre-requisite:
Tangents between two convex polygons
Algorithm:
Given the set of points for which we have to find the convex hull. Suppose we know the
convex hull of the left half points and the right half points, then the problem now is to
merge these two convex hulls and determine the convex hull for the complete set.
This can be done by finding the upper and lower tangent to the right and left convex hulls.
This is illustrated here Tangents between two convex polygons
267
Chapter 47. Convex Hull using Divide and Conquer Algorithm
Let the left convex hull be a and the right convex hull be b. Then the lower and upper
tangents are named as 1 and 2 respectively, as shown in the figure.
Then the red outline shows the final convex hull.
Now the problem remains, how to find the convex hull for the left and right half. Now
recursion comes into the picture, we divide the set of points until the number of points in
the set is very small, say 5, and we can find the convex hull for these points by the brute
algorithm. The merging of these halves would result in the convex hull for the complete set
of points.
Note:
We have used the brute algorithm to find the convex hull for a small number of points and
it has a time complexity of . But some people suggest the following, the convex
hull for 3 or fewer points is the complete set of points. This is correct but the problem
comes when we try to merge a left convex hull of 2 points and right convex hull of 3 points,
then the program gets trapped in an infinite loop in some special cases. So, to get rid of
this problem I directly found the convex hull for 5 or fewer points by algorithm,
which is somewhat greater but does not affect the overall complexity of the algorithm.
268
Chapter 47. Convex Hull using Divide and Conquer Algorithm
269
Chapter 47. Convex Hull using Divide and Conquer Algorithm
270
Chapter 47. Convex Hull using Divide and Conquer Algorithm
271
Chapter 47. Convex Hull using Divide and Conquer Algorithm
s.insert(a[i]);
s.insert(a[j]);
}
}
}
vector<pair<int, int>>ret;
for (auto e:s)
ret.push_back(e);
// Sorting the points in the anti-clockwise order
mid = {0, 0};
int n = ret.size();
for (int i=0; i<n; i++)
{
mid.first += ret[i].first;
mid.second += ret[i].second;
ret[i].first *= n;
ret[i].second *= n;
}
sort(ret.begin(), ret.end(), compare);
for (int i=0; i<n; i++)
ret[i] = make_pair(ret[i].first/n, ret[i].second/n);
return ret;
}
// Returns the convex hull for the given set of points
vector<pair<int, int>> divide(vector<pair<int, int>> a)
{
// If the number of points is less than 6 then the
// function uses the brute algorithm to find the
// convex hull
if (a.size() <= 5)
return bruteHull(a);
// left contains the left half points
// right contains the right half points
vector<pair<int, int>>left, right;
for (int i=0; i<a.size()/2; i++)
left.push_back(a[i]);
for (int i=a.size()/2; i<a.size(); i++)
right.push_back(a[i]);
// convex hull for the left and right sets
vector<pair<int, int>>left_hull = divide(left);
vector<pair<int, int>>right_hull = divide(right);
272
Chapter 47. Convex Hull using Divide and Conquer Algorithm
Output:
Convex Hull:
-5 -3
-1 -5
1 -4
0 0
-1 1
Time Complexity: The merging of the left and the right convex hulls take O(n) time
and as we are dividing the points into two equal parts, so the time complexity of the above
algorithm is O(n * log n).
Related Articles :
273
Chapter 47. Convex Hull using Divide and Conquer Algorithm
Source
https://www.geeksforgeeks.org/convex-hull-using-divide-and-conquer-algorithm/
274
Chapter 48
275
Chapter 48. Convex Hull | Set 1 (Jarvis’s Algorithm or Wrapping)
…..a) The next point q is the point such that the triplet (p, q, r) is counterclockwise for any
other point r.
…..b) next[p] = q (Store q as next of p in the output convex hull).
…..c) p = q (Set p as q for next iteration).
C++
276
Chapter 48. Convex Hull | Set 1 (Jarvis’s Algorithm or Wrapping)
if (val == 0) return 0; // colinear
return (val > 0)? 1: 2; // clock or counterclock wise
}
// Prints convex hull of a set of n points.
void convexHull(Point points[], int n)
{
// There must be at least 3 points
if (n < 3) return;
// Initialize Result
vector<Point> hull;
// Find the leftmost point
int l = 0;
for (int i = 1; i < n; i++)
if (points[i].x < points[l].x)
l = i;
// Start from leftmost point, keep moving counterclockwise
// until reach the start point again. This loop runs O(h)
// times where h is number of points in result or output.
int p = l, q;
do
{
// Add current point to result
hull.push_back(points[p]);
// Search for a point 'q' such that orientation(p, x,
// q) is counterclockwise for all points 'x'. The idea
// is to keep track of last visited most counterclock-
// wise point in q. If any point 'i' is more counterclock-
// wise than q, then update q.
q = (p+1)%n;
for (int i = 0; i < n; i++)
{
// If i is more counterclockwise than current q, then
// update q
if (orientation(points[p], points[i], points[q]) == 2)
q = i;
}
// Now q is the most counterclockwise with respect to p
// Set p as q for next iteration, so that q is added to
// result 'hull'
p = q;
277
Chapter 48. Convex Hull | Set 1 (Jarvis’s Algorithm or Wrapping)
Java
278
Chapter 48. Convex Hull | Set 1 (Jarvis’s Algorithm or Wrapping)
}
// Prints convex hull of a set of n points.
public static void convexHull(Point points[], int n)
{
// There must be at least 3 points
if (n < 3) return;
// Initialize Result
Vector<Point> hull = new Vector<Point>();
// Find the leftmost point
int l = 0;
for (int i = 1; i < n; i++)
if (points[i].x < points[l].x)
l = i;
// Start from leftmost point, keep moving
// counterclockwise until reach the start point
// again. This loop runs O(h) times where h is
// number of points in result or output.
int p = l, q;
do
{
// Add current point to result
hull.add(points[p]);
// Search for a point 'q' such that
// orientation(p, x, q) is counterclockwise
// for all points 'x'. The idea is to keep
// track of last visited most counterclock-
// wise point in q. If any point 'i' is more
// counterclock-wise than q, then update q.
q = (p + 1) % n;
for (int i = 0; i < n; i++)
{
// If i is more counterclockwise than
// current q, then update q
if (orientation(points[p], points[i], points[q])
== 2)
q = i;
}
// Now q is the most counterclockwise with
// respect to p. Set p as q for next iteration,
// so that q is added to result 'hull'
p = q;
279
Chapter 48. Convex Hull | Set 1 (Jarvis’s Algorithm or Wrapping)
} while (p != l); // While we don't come to first
// point
// Print Result
for (Point temp : hull)
System.out.println("(" + temp.x + ", " +
temp.y + ")");
}
/* Driver program to test above function */
public static void main(String[] args)
{
Point points[] = new Point[7];
points[0]=new Point(0, 3);
points[1]=new Point(2, 3);
points[2]=new Point(1, 1);
points[3]=new Point(2, 1);
points[4]=new Point(3, 0);
points[5]=new Point(0, 0);
points[6]=new Point(3, 3);
int n = points.length;
convexHull(points, n);
}
}
// This code is contributed by Arnav Kr. Mandal.
(0, 3)
(0, 0)
(3, 0)
(3, 3)
Time Complexity: For every point on the hull we examine all the other points to determine
the next point. Time complexity is ?(m * n) where n is number of input points and m is
number of output or hull points (m <= n). In worst case, time complexity is O(n 2 ). The
worst case occurs when all the points are on the hull (m = n)
Set 2- Convex Hull (Graham Scan)
Sources:
http://www.cs.uiuc.edu/~jeffe/teaching/373/notes/x05-convexhull.pdf
http://www.dcs.gla.ac.uk/~pat/52233/slides/Hull1x1.pdf
280
Chapter 48. Convex Hull | Set 1 (Jarvis’s Algorithm or Wrapping)
Source
https://www.geeksforgeeks.org/convex-hull-set-1-jarviss-algorithm-or-wrapping/
281
Chapter 49
282
Chapter 49. Convex Hull | Set 2 (Graham Scan)
2) Consider the remaining n-1 points and sort them by polor angle in counterclockwise order
around points[0]. If polor angle of two points is same, then put the nearest point first.
3 After sorting, check if two or more points have same angle. If two more points have same
angle, then remove all same angle points except the point farthest from P0. Let the size of
new array be m.
4) If m is less than 3, return (Convex Hull not possible)
5) Create an empty stack ‘S’ and push points[0], points[1] and points[2] to S.
6) Process remaining m-3 points one by one. Do following for every point ‘points[i]’
4.1) Keep removing points from stack while orientationof following 3 points is not
counterclockwise (or they don’t make a left turn).
a) Point next to top in stack
b) Point at the top of stack
c) points[i]
4.2) Push points[i] to S
5) Print contents of S
The above algorithm can be divided in two phases.
Phase 1 (Sort points): We first find the bottom-most point. The idea is to pre-process
points be sorting them with respect to the bottom-most point. Once the points are sorted,
they form a simple closed path (See following diagram).
What should be the sorting criteria? computation of actual angles would be inefficient
since trigonometric functions are not simple to evaluate. The idea is to use the orientation
to compare angles without actually computing them (See the compare() function below)
Phase 2 (Accept or Reject Points): Once we have the closed path, the next step is to
traverse the path and remove concave points on this path. How to decide which point to
remove and which to keep? Again, orientationhelps here. The first two points in sorted array
are always part of Convex Hull. For remaining points, we keep track of recent three points,
and find the angle formed by them. Let the three points be prev(p), curr(c) and next(n).
If orientation of these points (considering them in same order) is not counterclockwise, we
discard c, otherwise we keep it. Following diagram shows step by step process of this phase
283
Chapter 49. Convex Hull | Set 2 (Graham Scan)
284
Chapter 49. Convex Hull | Set 2 (Graham Scan)
}
// A utility function to swap two points
int swap(Point &p1, Point &p2)
{
Point temp = p1;
p1 = p2;
p2 = temp;
}
// A utility function to return square of distance
// between p1 and p2
int distSq(Point p1, Point p2)
{
return (p1.x - p2.x)*(p1.x - p2.x) +
(p1.y - p2.y)*(p1.y - p2.y);
}
// To find orientation of ordered triplet (p, q, r).
// The function returns following values
// 0 --> p, q and r are colinear
// 1 --> Clockwise
// 2 --> Counterclockwise
int orientation(Point p, Point q, Point r)
{
int val = (q.y - p.y) * (r.x - q.x) -
(q.x - p.x) * (r.y - q.y);
if (val == 0) return 0; // colinear
return (val > 0)? 1: 2; // clock or counterclock wise
}
// A function used by library function qsort() to sort an array of
// points with respect to the first point
int compare(const void *vp1, const void *vp2)
{
Point *p1 = (Point *)vp1;
Point *p2 = (Point *)vp2;
// Find orientation
int o = orientation(p0, *p1, *p2);
if (o == 0)
return (distSq(p0, *p2) >= distSq(p0, *p1))? -1 : 1;
return (o == 2)? -1: 1;
}
// Prints convex hull of a set of n points.
285
Chapter 49. Convex Hull | Set 2 (Graham Scan)
286
Chapter 49. Convex Hull | Set 2 (Graham Scan)
Output:
(0, 3)
(4, 4)
(3, 1)
(0, 0)
Time Complexity: Let n be the number of input points. The algorithm takes O(nLogn)
time if we use a O(nLogn) sorting algorithm.
The first step (finding the bottom-most point) takes O(n) time. The second step (sorting
287
Chapter 49. Convex Hull | Set 2 (Graham Scan)
points) takes O(nLogn) time. Third step takes O(n) time. In third step, every element is
pushed and popped at most one time. So the sixth step to process points one by one takes
O(n) time, assuming that the stack operations take O(1) time. Overall complexity is O(n)
+ O(nLogn) + O(n) + O(n) which is O(nLogn)
References:
Introduction to Algorithms 3rd Edition by Clifford Stein, Thomas H. Cormen, Charles E.
Leiserson, Ronald L. Rivest
http://www.dcs.gla.ac.uk/~pat/52233/slides/Hull1x1.pdf
Please write comments if you find anything incorrect, or you want to share more information
about the topic discussed above.
Source
https://www.geeksforgeeks.org/convex-hull-set-2-graham-scan/
288
Chapter 50
For finding the smallest rectangle you may take two of basic approach :
1. Consider origin of coordinate plane as smallest rectangle and then step by step keep
expanding it as per value of coordinates of points if they don’t lie inside the current
rectangle. This concept requires a little of complex logic to find the exact smallest
rectangle.
2. A very simple and efficient logic behind this is to find the smallest as well as largest
x & y coordinates among all given points and then the all possible four combinations
of these values result the four points of required rectangle as {Xmin, Ymin}, {Xmin,
Ymax}, {Xmax, Ymax}, {Xmax, Ymin}.
C++
289
Chapter 50. Coordinates of rectangle with given points lie inside
Java
290
Chapter 50. Coordinates of rectangle with given points lie inside
Python 3
291
Chapter 50. Coordinates of rectangle with given points lie inside
print("{",Xmax,", ",Ymax,"}",sep="" )
print("{",Xmax,", ",Ymin,"}",sep="" )
# driver program
X = [4, 3, 6, 1, -1, 12]
Y = [4, 1, 10, 3, 7, -1]
n = len(X)
printRect(X, Y, n)
# This code is contributed by
# Smitha Dinesh Semwal
C#
292
Chapter 50. Coordinates of rectangle with given points lie inside
PHP
<?php
// PHP Program to find smallest
// rectangle to conquer all points
// function to print coordinate
// of smallest rectangle
function printRect($X, $Y, $n)
{
// find Xmax and Xmin
$Xmax = max($X);
$Xmin = min($X);
// find Ymax and Ymin
$Ymax = max($Y);
$Ymin = min($Y);
// print all four coordinates
echo "{" , $Xmin , ", " , $Ymin , "}","\n";
echo "{" , $Xmin , ", " , $Ymax , "}" ,"\n";
echo "{" , $Xmax , ", " , $Ymax , "}","\n";
echo "{" , $Xmax , ", " , $Ymin , "}" ;
}
// Driver Code
$X = array(4, 3, 6, 1, -1, 12);
$Y = array(4, 1, 10, 3, 7, -1);
$n =count($X);
printRect($X, $Y, $n);
// This code is contributed by anuj_67.
?>
293
Chapter 50. Coordinates of rectangle with given points lie inside
Output:
{-1, -1}
{-1, 10}
{12, 10}
{12, -1}
Source
https://www.geeksforgeeks.org/coordinates-rectangle-given-points-lie-inside/
294
Chapter 51
Output: 6
We can use the Pick’s theorem, which states that the following equation holds true for a
simple Polygon.
Pick's Theeorem:
A = I + (B/2) -1
295
Chapter 51. Count Integral points inside a Triangle
296
Chapter 51. Count Integral points inside a Triangle
297
Chapter 51. Count Integral points inside a Triangle
Output:
Source
https://www.geeksforgeeks.org/count-integral-points-inside-a-triangle/
298
Chapter 52
We can solve above problem by following approach – For each point p, calculate its slope
with other points and use a map to record how many points have same slope, by which we
can find out how many points are on same line with p as their one point. For each point
keep doing the same thing and update the maximum number of point count found so far.
Some things to note in implementation are:
1) if two point are (x1, y1) and (x2, y2) then their slope will be (y2 – y1) / (x2 – x1)
which can be a double value and can cause precision problems. To get rid of the precision
problems, we treat slope as pair ((y2 – y1), (x2 – x1)) instead of ratio and reduce pair by
their gcd before inserting into map. In below code points which are vertical or repeated are
treated separately.
2) If we use unordered_map in c++ or HashMap in Java for storing the slope pair, then
total time complexity of solution will be O(n^2)
299
Chapter 52. Count maximum points on same line
300
Chapter 52. Count maximum points on same line
yDif /= g;
xDif /= g;
// increasing the frequency of current slope
// in map
slopeMap[make_pair(yDif, xDif)]++;
curMax = max(curMax, slopeMap[make_pair(yDif, xDif)]);
}
curMax = max(curMax, verticalPoints);
}
// updating global maximum by current point's maximum
maxPoint = max(maxPoint, curMax + overlapPoints + 1);
// printf("maximum colinear point
// which contains current point
// are : %d\n", curMax + overlapPoints + 1);
slopeMap.clear();
}
return maxPoint;
}
// Driver code
int main()
{
const int N = 6;
int arr[N][2] = {{-1, 1}, {0, 0}, {1, 1}, {2, 2},
{3, 3}, {3, 4}};
vector< pair<int, int> > points;
for (int i = 0; i < N; i++)
points.push_back(make_pair(arr[i][0], arr[i][1]));
cout << maxPointOnSameLine(points) << endl;
return 0;
}
Output:
Improved By : PortgasDAce
301
Chapter 52. Count maximum points on same line
Source
https://www.geeksforgeeks.org/count-maximum-points-on-same-line/
302
Chapter 53
Count of acute, obtuse and right triangles with given sides - GeeksforGeeks
Given an array of n positive distinct integers representing lengths of lines that can form
triangle. The task is to find the number of acute triangles, obtuse triangles, and right
triangles separately that can be formed from the given array.
Examples:
303
Chapter 53. Count of acute, obtuse and right triangles with given sides
304
Chapter 53. Count of acute, obtuse and right triangles with given sides
if (b[i]+b[j]==b[p])
{
// All triangle between j and p are acute
// triangles. So add p - j - 1 in x.
x += max(p - j - 1, 0);
// Increment y by 1.
y++;
// All triangle between q and p are acute
// triangles. So add q - p in z.
z += q - p;
}
// If no right triangle
else
{
// All triangle between j and p are acute
// triangles. So add p - j in x.
x += max(p - j, 0);
// All triangle between q and p are acute
// triangles. So add q - p in z.
z += q - p;
}
}
}
cout << "Acute Triangle: " << x << endl;
cout << "Right Triangle: " << y << endl;
cout << "Obtuse Triangle: " << z << endl;
}
// Driver Code
int main()
{
int arr[] = {2, 3, 9, 10, 12, 15};
int n = sizeof(arr)/sizeof(arr[0]);
findTriangle(arr, n);
return 0;
}
Output:
Acute Triangle: 2
Right Triangle: 1
Obtuse Triangle: 4
305
Chapter 53. Count of acute, obtuse and right triangles with given sides
Source
https://www.geeksforgeeks.org/count-of-acute-obtuse-and-right-triangles-with-given-sides/
306
Chapter 54
Count of different straight lines with total n points with m collinear - GeeksforGeeks
There are ‘n’ points in a plane out of which ‘m points are collinear. How many different
straight lines can form?
Examples:
Input : n = 3, m = 3
Output : 1
We can form only 1 distinct straight line
using 3 collinear points
Input : n = 10, m = 4
Output : 40
307
Chapter 54. Count of different straight lines with total n points with m collinear
Since straight lines formed by these 4 points are sane, straight lines formed by
them will reduce to only one.
Required number of straight lines formed = 10 C2 – 4 C2 + 1 = 45 – 6 + 1 = 40
C++
308
Chapter 54. Count of different straight lines with total n points with m collinear
/* driver function*/
int main()
{
int n = 4, m = 3 ;
cout << count_Straightlines(n, m);
return 0;
}
Java
309
Chapter 54. Count of different straight lines with total n points with m collinear
// Driver function
public static void main(String argc[])
{
int n = 4, m = 3;
System.out.println(count_Straightlines(n, m));
}
// This code is contributed by Sagar Shukla
}
Python
310
Chapter 54. Count of different straight lines with total n points with m collinear
print( count_Straightlines(n, m) );
# This code is contributed by "rishabh_jain".
C#
311
Chapter 54. Count of different straight lines with total n points with m collinear
}
}
// This code is contributed by vt_m.
PHP
<?php
// PHP program to count number of straight lines
// with n total points, out of which m are
// collinear.
// Returns value of binomial coefficient
function nCk($n, $k)
{
$C = array_fill(0, $k + 1, NULL);
$C[0] = 1; // nC0 is 1
for ($i = 1; $i <= $n; $i++)
{
// Compute next row of pascal triangle
// using the previous row
for ($j = min($i, $k); $j > 0; $j--)
$C[$j] = $C[$j] + $C[$j-1];
}
return $C[$k];
}
// function to calculate
// number of straight lines
// can be formed
function count_Straightlines($n, $m)
{
return (nCk($n, 2) - nCk($m, 2) + 1);
}
// Driver Code
$n = 4;
$m = 3;
echo(count_Straightlines($n, $m));
312
Chapter 54. Count of different straight lines with total n points with m collinear
Output:
Source
https://www.geeksforgeeks.org/count-different-straight-lines-total-n-points-m-collinear/
313
Chapter 55
Count of obtuse angles in a circle with ’k’ equidistant points between 2 given points -
GeeksforGeeks
A circle is given with k equidistant points on its circumference. 2 points A and B are given
in the circle. Find the count of all obtuse angles (angles larger than 90 degree) formed from
/_ACB, where C can be any point in circle other than A or B.
Note :
A and B are not equal.
A < B.
Points are between 1 and K(both inclusive).
314
Chapter 55. Count of obtuse angles in a circle with ‘k’ equidistant points between 2 given
points
Examples :
Input : K = 6, A = 1, B = 3.
Output : 1
Explanation : In the circle with 6
equidistant points, when C = 2 i.e.
/_123, we get obtuse angle.
Input : K = 6, A = 1, B = 4.
Output : 0
Explanation : In this circle, there
is no such C that form an obtuse angle.
It can be observed that if A and B have equal elements in between them, there can’t be any
C such that ACB is obtuse. Also, the number of possible obtuse angles are the smaller arc
between A and B.
Below is the implementation :
C++
315
Chapter 55. Count of obtuse angles in a circle with ‘k’ equidistant points between 2 given
points
Java
316
Chapter 55. Count of obtuse angles in a circle with ‘k’ equidistant points between 2 given
points
}
// Driver Program to test above function
public static void main(String arg[])
{
int k = 6, a = 1, b = 3;
System.out.print(countObtuseAngles(a, b, k));
}
}
// This code is contributed by Anant Agarwal.
Python
C#
317
Chapter 55. Count of obtuse angles in a circle with ‘k’ equidistant points between 2 given
points
PHP
<?php
// PHP program to count number
// of obtuse angles for given
// two points.
function countObtuseAngles($a, $b, $k)
{
// There are two arcs connecting a
// and b. Let us count points on
// both arcs.
$c1 = ($b - $a) - 1;
$c2 = ($k - $b) + ($a - 1);
318
Chapter 55. Count of obtuse angles in a circle with ‘k’ equidistant points between 2 given
points
// Both arcs have same number of
// points
if ($c1 == $c2)
return 0;
// Points on smaller arc is answer
return min($c1, $c2);
}
// Driver code
$k = 6; $a = 1; $b = 3;
echo countObtuseAngles($a, $b, $k);
// This code is contributed by aj_36
?>
Output :
Source
https://www.geeksforgeeks.org/count-obtuse-angles-circle-k-equidistant-points-2-given-points/
319
Chapter 56
Count of parallelograms in a
plane
Input : points[] = {(0, 0), (0, 2), (2, 2), (4, 2),
(1, 4), (3, 4)}
Output : 2
Two Parallelograms are possible by choosing above
given point as vertices, which are shown in below
diagram.
We can solve this problem by using a special property of parallelograms that diagonals of a
parallelogram intersect each other in the middle. So if we get such a middle point which is
middle point of more than one line segment, then we can conclude that a parallelogram exists,
more accurately if a middle point occurs x times, then diagonals of possible parallelograms
can be chosen in x C2 ways, i.e. there will be x*(x-1)/2 parallelograms corresponding to this
particular middle point with a frequency x. So we iterate over all pair of points and we
calculate their middle point and increase frequency of middle point by 1. At the end, we
count number of parallelograms according to the frequency of each distinct middle point as
explained above. As we just need frequency of middle point, division by 2 is ignored while
calculating middle point for simplicity.
320
Chapter 56. Count of parallelograms in a plane
#include <bits/stdc++.h>
using namespace std;
// Returns count of Parallelograms possible
// from given points
int countOfParallelograms(int x[], int y[], int N)
{
// Map to store frequency of mid points
map<pair<int, int>, int> cnt;
for (int i=0; i<N; i++)
{
for (int j=i+1; j<N; j++)
{
// division by 2 is ignored, to get
// rid of doubles
int midX = x[i] + x[j];
int midY = y[i] + y[j];
// increase the frequency of mid point
cnt[make_pair(midX, midY)]++;
}
}
// Iterating through all mid points
int res = 0;
for (auto it = cnt.begin(); it != cnt.end(); it++)
{
int freq = it->second;
// Increase the count of Parallelograms by
// applying function on frequency of mid point
res += freq*(freq - 1)/2
}
return res;
}
// Driver code to test above methods
int main()
{
int x[] = {0, 0, 2, 4, 1, 3};
int y[] = {0, 2, 2, 2, 4, 4};
int N = sizeof(x) / sizeof(int);
cout << countOfParallelograms(x, y, N) << endl;
return 0;
}
321
Chapter 56. Count of parallelograms in a plane
Output:
Source
https://www.geeksforgeeks.org/count-parallelograms-plane/
322
Chapter 57
Input : N = 2
Output : 2
Explanation: If points are numbered 1 to 4 in
clockwise direction, then different ways to
draw chords are:
{(1-2), (3-4)} and {(1-4), (2-3)}
Input : N = 1
Output : 1
Explanation: Draw a chord between points 1 and 2.
If we draw a chord between any two points, can you observe the current set of points
getting broken into two smaller sets S_1 and S_2. If we draw a chord from a point in S_1
to a point in S_2, it will surely intersect the chord we’ve just drawn.
So, we can arrive at a recurrence that Ways(n) = sum[i = 0 to n-1] { Ways(i)*Ways(n-i-1)
}.
Here we iterate over i, assuming that size of one of the sets is i and size of another set
automatically is (n-i-1) since we’ve already used a pair of points and i pair of points in one set.
C++
323
Chapter 57. Count ways to divide circle using N non-intersecting chords
Java
324
Chapter 57. Count ways to divide circle using N non-intersecting chords
class GFG {
static int chordCnt(int A)
{
// n = no of points required
int n = 2 * A;
// dp array containing the sum
int[] dpArray = new int[n + 1];
dpArray[0] = 1;
dpArray[2] = 1;
for (int i = 4; i <= n; i += 2) {
for (int j = 0; j < i - 1; j += 2)
{
dpArray[i] += (dpArray[j] *
dpArray[i - 2 - j]);
}
}
// returning the required number
return dpArray[n];
}
public static void main(String[] args)
{
int N;
N = 2;
System.out.println(chordCnt(N));
N = 1;
System.out.println(chordCnt(N));
N = 4;
System.out.println(chordCnt(N));
}
}
// This code is contributed by Gitanjali.
Python 3
325
Chapter 57. Count ways to divide circle using N non-intersecting chords
dpArray[0] = 1
dpArray[2] = 1
for i in range(4, n + 1, 2):
for j in range(0, i-1, 2):
dpArray[i] += (dpArray[j]*dpArray[i-2-j])
# returning the required number
return int(dpArray[n])
# driver code
N = 2
print(chordCnt( N))
N = 1
print(chordCnt( N))
N = 4
print(chordCnt( N))
C#
326
Chapter 57. Count ways to divide circle using N non-intersecting chords
Output:
2
1
14
Source
https://www.geeksforgeeks.org/count-ways-divide-circle-using-n-non-intersecting-chords/
327
Chapter 58
328
Chapter 58. Deleting points from Convex Hull
329
Chapter 58. Deleting points from Convex Hull
330
Chapter 58. Deleting points from Convex Hull
}
int lowera = inda, lowerb = indb;
vector<pair<int, int> > ret;
//ret contains the convex hull after merging the two convex hulls
//with the points sorted in anti-clockwise order
int ind = uppera;
ret.push_back(a[uppera]);
while (ind != lowera)
{
ind = (ind+1)%n1;
ret.push_back(a[ind]);
}
ind = lowerb;
ret.push_back(b[lowerb]);
while (ind != upperb)
{
ind = (ind+1)%n2;
ret.push_back(b[ind]);
}
return ret;
}
// Brute force algorithm to find convex hull for a set
// of less than 6 points
vector<pair<int, int> > bruteHull(vector<pair<int, int> > a)
{
// Take any pair of points from the set and check
// whether it is the edge of the convex hull or not.
// if all the remaining points are on the same side
// of the line then the line is the edge of convex
// hull otherwise not
set<pair<int, int> >s;
for (int i=0; i<a.size(); i++)
{
for (int j=i+1; j<a.size(); j++)
{
int x1 = a[i].first, x2 = a[j].first;
int y1 = a[i].second, y2 = a[j].second;
int a1 = y1-y2;
int b1 = x2-x1;
int c1 = x1*y2-y1*x2;
int pos = 0, neg = 0;
331
Chapter 58. Deleting points from Convex Hull
332
Chapter 58. Deleting points from Convex Hull
333
Chapter 58. Deleting points from Convex Hull
int main()
{
vector<pair<int, int> > a;
a.push_back(make_pair(0, 0));
a.push_back(make_pair(1, -4));
a.push_back(make_pair(-1, -5));
a.push_back(make_pair(-5, -3));
a.push_back(make_pair(-3, -1));
a.push_back(make_pair(-1, -3));
a.push_back(make_pair(-2, -2));
a.push_back(make_pair(-1, -1));
a.push_back(make_pair(-2, -1));
a.push_back(make_pair(-1, 1));
int n = a.size();
// sorting the set of points according
// to the x-coordinate
sort(a.begin(), a.end());
vector<pair<int, int> >hull = findHull(a);
cout << "Convex hull:\n";
for (auto e : hull)
cout << e.first << " "
<< e.second << endl;
pair<int, int> p = make_pair(-5, -3);
removePoint(a, hull, p);
cout << "\nModified Convex Hull:\n";
for (auto e:hull)
cout << e.first << " "
<< e.second << endl;
return 0;
}
Output:
convex hull:
-3 0
-1 -9
2 -6
5 3
2 5
Time Complexity:
334
Chapter 58. Deleting points from Convex Hull
It is simple to see that the maximum time taken per query is the time taken to construct
the convex hull which is O(n*logn). So, the overall complexity is O(q*n*logn), where q is
the number of points to be deleted.
Source
https://www.geeksforgeeks.org/deleting-points-convex-hull/
335
Chapter 59
The point might lie behind the line segment, in that case we assume imaginary line by
extending the line segment and determine the direction of point.
336
Chapter 59. Direction of a Point from a Line Segment
* There are only three cases, either the point is on left side, or right side or on the line
segment itself.
This is a very fundamental Problem and is commonly encountered for directions in online
map,
Example : Suppose a user A has to go to Point C in the following map, the user first
reaches point B but after that how does user A know that whether he has to make a right
turn or left turn.
Knowing the direction of a point from a line segment also acts a building block to solve
more complicated problem such as :
Line segment Intersection : finding if two line segment intersect
337
Chapter 59. Direction of a Point from a Line Segment
Right Direction
Source
https://www.geeksforgeeks.org/direction-point-line-segment/
338
Chapter 60
339
Chapter 60. Distance between a point and a Plane in 3 D
340
Chapter 60. Distance between a point and a Plane in 3 D
Examples :
Approach: The perpendicular distance (i.e shortest distance) from a given point to a Plane
is the perpendicular distance from that point to the given plane. Let the co-ordinate of the
given point be (x1, y1, z1)
and equation of the plane be given by the equation a * x + b * y + c * z + d = 0, where a,
b and c are real constants.
The formula for distance between a point and Plane in 3-D is given by:
341
Chapter 60. Distance between a point and a Plane in 3 D
float d = 8;
// Function call
shortest_distance(x1, y1, z1, a, b, c, d);
}
// This code is contributed
// by Amber_Saxena.
Java
342
Chapter 60. Distance between a point and a Plane in 3 D
}
// This code is contributed
// by Amber_Saxena.
Python
C#
// C# program to find the
// Perpendicular(shortest)
// distance between a point
// and a Plane in 3 D.
using System;
class GFG
{
// Function to find distance
static void shortest_distance(float x1, float y1,
float z1, float a,
float b, float c,
float d)
{
343
Chapter 60. Distance between a point and a Plane in 3 D
d = Math.Abs((a * x1 + b *
y1 + c * z1 + d));
float e = (float)Math.Sqrt(a * a + b *
b + c * c);
Console.Write(“Perpendicular distance ” +
“is ” + d / e);
}
// Driver code
public static void Main()
{
float x1 = 4;
float y1 = -4;
float z1 = 3;
float a = 2;
float b = -2;
float c = 5;
float d = 8;
// Function call
shortest_distance(x1, y1, z1,
a, b, c, d);
}
}
// This code is contributed
// by ChitraNayal
PHP
<?php
// PHP program to find the
// Perpendicular(shortest)
// distance between a point
// and a Plane in 3 D.
// Function to find distance
function shortest_distance($x1, $y1, $z1,
$a, $b, $c, $d)
{
$d = abs(($a * $x1 + $b * $y1 +
$c * $z1 + $d));
$e = sqrt($a * $a + $b *
$b + $c * $c);
echo "Perpendicular distance is ". $d / $e;
}
// Driver Code
$x1 = 4;
$y1 = -4;
344
Chapter 60. Distance between a point and a Plane in 3 D
$z1 = 3;
$a = 2;
$b = -2;
$c = 5;
$d = 8;
// function call
shortest_distance($x1, $y1, $z1,
$a, $b, $c, $d);
// This code is contributed
// by Amber_Saxena.
?>
Output:
Source
https://www.geeksforgeeks.org/distance-between-a-point-and-a-plane-in-3-d/
345
Chapter 61
346
Chapter 61. Distance between two parallel Planes in 3-D
347
Chapter 61. Distance between two parallel Planes in 3-D
Examples :
=> a1 / a2 = b1 / b2 = c1 / c2
Find a point in any one plane such that the distance from that point to the other plane that
will be the distance between those two planes. The distance can be calculated by using the
formulae:
348
Chapter 61. Distance between two parallel Planes in 3-D
Java
349
Chapter 61. Distance between two parallel Planes in 3-D
Python
350
Chapter 61. Distance between two parallel Planes in 3-D
C#
// C# program to find the Distance
// between two parallel Planes in 3 D.
using System;
class GFG
{
// Function to find distance
static void distance(float a1, float b1,
float c1, float d1,
float a2, float b2,
float c2, float d2)
{
float z1, d;
if (a1 / a2 == b1 / b2 &&
b1 / b2 == c1 / c2)
{
z1 =-d1 / c1;
d = Math.Abs((c2 * z1 + d2)) /
(float)(Math.Sqrt(a2 * a2 + b2 *
b2 + c2 * c2));
Console.Write(“Perpendicular distance is ” + d);
}
else
Console.Write(“Planes are not parallel”);
}
// Driver code
public static void Main()
351
Chapter 61. Distance between two parallel Planes in 3-D
{
float a1 = 1;
float b1 = 2;
float c1 = -1;
float d1 = 1;
float a2 = 3;
float b2 = 6;
float c2 = -3;
float d2 = -4;
distance(a1, b1, c1, d1,
a2, b2, c2, d2);// Fxn cal
}
}
// This code is contributed
// by ChitraNayal
PHP
<?php
// PHP program to find the Distance
// between two parallel Planes in 3 D
// Function to find distance
function distance($a1, $b1, $c1,
$d1, $a2, $b2,
$c2, $d2)
{
if ($a1 / $a2 == $b1 / $b2 &&
$b1 / $b2 == $c1 / $c2)
{
$x1 = $y1 = 0;
$z1 =- $d1 / $c1;
$d = abs(($c2 * $z1 + $d2)) /
(sqrt($a2 * $a2 + $b2 *
$b2 + $c2 * $c2));
echo "Perpendicular distance is ", $d;
}
else
echo "Planes are not parallel";
}
// Driver Code
$a1 = 1;
$b1 = 2;
$c1 = -1;
$d1 = 1;
$a2 = 3;
$b2 = 6;
352
Chapter 61. Distance between two parallel Planes in 3-D
$c2 = -3;
$d2 = -4;
distance($a1, $b1, $c1, $d1,
$a2, $b2, $c2, $d2);
// This code is contributed
// by Amber_Saxena.
?>
Output:
Source
https://www.geeksforgeeks.org/distance-between-two-parallel-planes-in-3-d/
353
Chapter 62
Divide cuboid into cubes such that sum of volumes is maximum - GeeksforGeeks
Given the length, breadth, height of a cuboid. The task is to divide the given cuboid in
minimum number of cubes such that size of all cubes is same and sum of volumes of cubes
is maximum.
Examples:
Input : l = 2, b = 4, h = 6
Output : 2 6
A cuboid of length 2, breadth 4 and
height 6 can be divided into 6 cube
of side equal to 2.
Volume of cubes = 6*(2*2*2) = 6*8 = 48.
Volume of cuboid = 2*4*6 = 48.
Input : 1 2 3
Output : 1 6
First of all, we are not allowed to waste volume of cuboid as we meed maximum volume
sum. So, each side should be completely divide among all cubes. And since each of three
side of cubes are equal, so each side of the cuboid need to be divisible by same number,
say x, which will going to be the side of the cube. So, we have to maximize this x, which
will divide given length, breadth and height. This x will be maximum only if it is greatest
common divisor of given length, breadth and height. So, the length of the cube will be GCD
of length, breadth and height.
354
Chapter 62. Divide cuboid into cubes such that sum of volumes is maximum
Now, to compute number of cubes, we know total volume of cuboid and can find volume of
one cube (since side is already calculated). So, total number of cubes is equal to (volume of
cuboid)/(volume of cube) i.e (l * b * h)/(x * x * x).
Below is implementation of this approach:
C++
Java
355
Chapter 62. Divide cuboid into cubes such that sum of volumes is maximum
return m;
else if(n > m)
return gcd(n,m);
else
return gcd(n, m % n);
}
// Print the maximum side and no
// of cube.
static void maximizecube(int l, int b,
int h)
{
// GCD to find side.
int side = gcd(l, gcd(b, h));
// dividing to find number of cubes.
int num = l / side;
num = (num * b / side);
num = (num * h / side);
System.out.println( side + " " + num);
}
/* Driver program */
public static void main(String[] args)
{
int l = 2, b = 4, h = 6;
maximizecube(l, b, h);
}
}
// This code is contributed by Arnav Kr. Mandal.
Python3
356
Chapter 62. Divide cuboid into cubes such that sum of volumes is maximum
C#
357
Chapter 62. Divide cuboid into cubes such that sum of volumes is maximum
PHP
<?php
// PHP program to find optimal way
// to break cuboid into cubes.
// Recursive function to
// return gcd of a and b
function __gcd($a, $b)
{
// Everything divides 0
if($a == 0 or $b == 0)
return 0 ;
// base case
if($a == $b)
return $a ;
// a is greater
if($a > $b)
return __gcd($a - $b , $b ) ;
return __gcd($a , $b - $a) ;
}
// Print the maximum side and no of cube.
function maximizecube($l, $b, $h)
{
// GCD to find side.
$side = __gcd($l, __gcd($b, $h));
// dividing to find number of cubes.
$num = $l / $side;
$num = ($num * $b / $side);
$num = ($num * $h / $side);
358
Chapter 62. Divide cuboid into cubes such that sum of volumes is maximum
Output:
2 6
Improved By : vt_m
Source
https://www.geeksforgeeks.org/divide-cuboid-cubes-sum-volumes-maximum/
359
Chapter 63
360
Chapter 63. Draw geometric shapes on images using OpenCV
Output :
Now, let’s draw some geometric shapes on this solid black image.
Draw a line :
361
Chapter 63. Draw geometric shapes on images using OpenCV
Output :
Draw a rectangle :
362
Chapter 63. Draw geometric shapes on images using OpenCV
import numpy as np
import cv2
# Creating a black image with 3
# channels RGB and unsigned int datatype
img = np.zeros((400, 400, 3), dtype = "uint8")
# Creating rectangle
cv2.rectangle(img, (30, 30), (300, 200), (0, 255, 0), 5)
cv2.imshow('dark', img)
# Allows us to see image
# untill closed forcefully
cv2.waitKey(0)
cv2.destroyAllWindows()
Output :
363
Chapter 63. Draw geometric shapes on images using OpenCV
Draw a Circle :
Output :
364
Chapter 63. Draw geometric shapes on images using OpenCV
Writing text :
365
Chapter 63. Draw geometric shapes on images using OpenCV
Output :
• Drawing geometrical shapes can help us highlight the particular portions of an image.
• Geometrical shapes like line can help us point or identify particular regions in image.
• Writing text on certain regions of images can add description to that region.
Reference :
https://docs.opencv.org/2.4/modules/core/doc/drawing_functions.html
366
Chapter 63. Draw geometric shapes on images using OpenCV
Source
https://www.geeksforgeeks.org/draw-geometric-shapes-images-using-opencv/
367
Chapter 64
Input :
Convex Hull : (0, 0), (3, -1), (4, 5), (-1, 4)
Point to add : (100, 100)
Output :
New convex hull : (-1, 4) (0, 0) (3, -1) (100, 100)
We first check whether the point is inside the given convex hull or not. If it is, then nothing
has to be done we directly return the given convex hull. If the point is outside the convex
hull, we find the lower and upper tangents, and then merge the point with the given convex
hull to find the new convex hull, as shown in the figure.
368
Chapter 64. Dynamic Convex hull | Adding Points to an Existing Convex Hull
The red outline shows the new convex hull after merging the point and the given convex
hull.
To find the upper tangent, we first choose a point on the hull that is nearest to the given
point. Then while the line joining the point on the convex hull and the given point crosses
the convex hull, we move anti-clockwise till we get the tangent line.
The figure shows the moving of the point on the convex hull for finding the upper tangent.
Note: It is assumed here that the input of the initial convex hull is in the anti-clockwise
order, otherwise we have to first sort them in anti-clockwise order then apply the following
code.
Code:
369
Chapter 64. Dynamic Convex hull | Adding Points to an Existing Convex Hull
370
Chapter 64. Dynamic Convex hull | Adding Points to an Existing Convex Hull
371
Chapter 64. Dynamic Convex hull | Adding Points to an Existing Convex Hull
Output:
Time Complexity:
The time complexity of the above algorithm is O(n*q), where q is the number of points to
be added.
Source
https://www.geeksforgeeks.org/dynamic-convex-hull-adding-points-existing-convex-hull/
372
Chapter 65
Enneadecagonal number
Input : 4
Output :106
Input :10
Output :775
373
Chapter 65. Enneadecagonal number
C++
Java
374
Chapter 65. Enneadecagonal number
{
int n = 6;
System.out.print(n + "th Enneadecagonal number :");
System.out.println( nthEnneadecagonal(n));
}
}
// This code is contributed by m_kit.
Python3
C#
// C# program to find
// nth Enneadecagonal number
using System;
class GFG
{
// Function to calculate
// Enneadecagonal number
static int nthEnneadecagonal(int n)
{
// Formula for finding
// nth Enneadecagonal number
return (17 * n * n - 15 * n) / 2;
375
Chapter 65. Enneadecagonal number
}
// Driver Code
static public void Main ()
{
int n = 6;
Console.Write(n + "th Enneadecagonal number :");
Console.WriteLine( nthEnneadecagonal(n));
}
}
// This code is contributed by aj_36
PHP
<?php
// PHP program to find
// nth Enneadecagonal number
// Function to calculate
// Enneadecagonal number
function nthEnneadecagonal($n)
{
// Formula for finding
// nth Enneadecagonal number
return (17 * $n * $n -
15 * $n) / 2;
}
// Driver Code
$n = 6;
echo $n , "th Enneadecagonal number :" ,
nthEnneadecagonal($n);
// This code is contributed by ajit
?>
Output :
Reference: https://en.wikipedia.org/wiki/Polygonal_number
Improved By : jit_t
376
Chapter 65. Enneadecagonal number
Source
https://www.geeksforgeeks.org/enneadecagonal-number/
377
Chapter 66
Equable Shapes
We can find area of polygon using shoelace formula which is described in Area of a polygon
with given n ordered vertices. We can also find its perimeter simply by adding distances
between adjacent points.
C++
378
Chapter 66. Equable Shapes
379
Chapter 66. Equable Shapes
equableShape(X, Y, n);
return 0;
}
Java
380
Chapter 66. Equable Shapes
System.out.println("Equable Shape");
else
System.out.println("Not Equable Shape");
}
// Driver program to test above function
public static void main(String[] args)
{
double X[] = { 0, 5, 0 };
double Y[] = { 0, 0, 12 };
int n = X.length;
equableShape(X, Y, n);
}
}
Python 3
381
Chapter 66. Equable Shapes
return perimeter
# To find equable shape
def equableShape(X, Y, n):
# Find area and perimeter of polygon if
# they are equal then it is equable shape
if (polygonPerimeter(X, Y, n) == polygonArea(X, Y, n)):
print("Equable Shape")
else:
print("Not Equable Shape")
# Driver program to test above function
X = [ 0, 5, 0 ]
Y = [ 0, 0, 12 ]
n = len(X)
equableShape(X, Y, n)
# This code is contributed by Azkia Anam.
C#
382
Chapter 66. Equable Shapes
double []Y,
int n)
{
double perimeter = 0.0;
// Calculate value of perimeter
int j = n - 1;
for (int i = 0; i < n; i++) {
perimeter += Math.Sqrt((X[j] - X[i]) *
(X[j] - X[i]) +
(Y[j] - Y[i]) *
(Y[j] - Y[i]));
j = i; // j is previous vertex to i
}
return perimeter;
}
// To find equable shape
static void equableShape(double []X,
double []Y,
int n)
{
// Find area and perimeter of
// polygon if they are equal
// then it is equable shape
if (polygonPerimeter(X, Y, n) ==
polygonArea(X, Y, n))
Console.WriteLine("Equable Shape");
else
Console.WriteLine("Not Equable Shape");
}
// Driver Code
public static void Main(String []args)
{
double []X = {0, 5, 0};
double []Y = {0, 0, 12};
int n = X.Length;
// Calling Function
equableShape(X, Y, n);
}
}
// This Code is contributed by vt_m.
383
Chapter 66. Equable Shapes
PHP
<?php
// PHP program to find
// equable shape
// To calculate area
// of polygon
function polygonArea($X, $Y, $n)
{
$area = 0.0;
// Calculate value of area
// using shoelace formula
$j = $n - 1;
for ($i = 0; $i < $n; $i++)
{
$area += ($X[$j] + $X[$i]) *
($Y[$j] - $Y[$i]);
// j is previous vertex to i
$j = $i;
}
return abs($area / 2.0);
}
// To calculate perimeter of polygon
function polygonPerimeter($X, $Y, $n)
{
$perimeter = 0.0;
// Calculate value of perimeter
$j = $n - 1;
for ($i = 0; $i < $n; $i++)
{
$perimeter += sqrt(($X[$j] - $X[$i]) *
($X[$j] - $X[$i]) +
($Y[$j] - $Y[$i]) *
($Y[$j] - $Y[$i]));
// j is previous vertex to i
$j = $i;
}
return $perimeter;
}
384
Chapter 66. Equable Shapes
// To find equable shape
function equableShape($X, $Y, $n)
{
// Find area and perimeter of
// polygon if they are equal
// then it is equable shape
if (polygonPerimeter($X, $Y, $n) ==
polygonArea($X, $Y, $n))
echo "Equable Shape";
else
echo "Not Equable Shape";
}
// Driver Code
$X = array( 0, 5, 0 );
$Y = array( 0, 0, 12 );
$n = sizeof($X);
equableShape($X, $Y, $n);
// This code is contributed by ajit
?>
Output :
Equable Shape
Reference:
https://en.wikipedia.org/wiki/Equable_shape
Improved By : vt_m, jit_t
Source
https://www.geeksforgeeks.org/equable-shapes/
385
Chapter 67
Examples:
386
Chapter 67. Find Corners of Rectangle using mid points
Input : p = (1, 0)
q = (1, 2)
L = 2
Output : (0, 0), (0, 2), (2, 2), (2, 0)
Explanation:
The printed points form a rectangle which
satisfy the input constraints.
Input : p = (1, 1)
q = (-1, -1)
L = 2*sqrt(2)
Output : (0, 2), (-2, 0), (0, -2), (2, 0)
The first two cases are trivial and can easily be solved using basic geometry. For the third
case we need to apply some mathematical concepts to find the points.
Consider the above diagram for clarity. We have the co-ordinates of p and q. Thus we can
find the slope of AD and BC (As pq is perpendicular to AD). Once we have the slope of AD,
we can find the equation of straight line passing through AD. Now we can apply distance
formula to obtain the displacements along X and Y axes.
If slope of AD = m, then
m = (p.x- q.x)/(q.y - p.y)
Similarly, dy = m*L/(2*sqrt(1+m*m))
Now we can simply find the co-ordinates of 4 corners by simply adding and subtracting the
displacements obtained accordingly.
Below is the implementation in C++.
387
Chapter 67. Find Corners of Rectangle using mid points
// Structure to represent a co-ordinate point
struct Point
{
float x, y;
Point()
{
x = y = 0;
}
Point(float a, float b)
{
x = a, y = b;
}
};
// This function receives two points and length
// of the side of rectangle and prints the 4
// corner points of the rectangle
void printCorners(Point p, Point q, float l)
{
Point a, b, c, d;
// horizontal rectangle
if (p.x == q.x)
{
a.x = p.x - (l/2.0);
a.y = p.y;
d.x = p.x + (l/2.0);
d.y = p.y;
b.x = q.x - (l/2.0);
b.y = q.y;
c.x = q.x + (l/2.0);
c.y = q.y;
}
// vertical rectangle
else if (p.y == q.y)
{
a.y = p.y - (l/2.0);
a.x = p.x;
d.y = p.y + (l/2.0);
d.x = p.x;
b.y = q.y - (l/2.0);
388
Chapter 67. Find Corners of Rectangle using mid points
b.x = q.x;
c.y = q.y + (l/2.0);
c.x = q.x;
}
// slanted rectangle
else
{
// calculate slope of the side
float m = (p.x-q.x)/float(q.y-p.y);
// calculate displacements along axes
float dx = (l /sqrt(1+(m*m))) *0.5 ;
float dy = m*dx;
a.x = p.x - dx;
a.y = p.y - dy;
d.x = p.x + dx;
d.y = p.y + dy;
b.x = q.x - dx;
b.y = q.y - dy;
c.x = q.x + dx;
c.y = q.y + dy;
}
cout << a.x << ", " << a.y << " n"
<< b.x << ", " << b.y << "n";
<< c.x << ", " << c.y << " n"
<< d.x << ", " << d.y << "nn";
}
// Driver code
int main()
{
Point p1(1, 0), q1(1, 2);
printCorners(p1, q1, 2);
Point p(1, 1), q(-1, -1);
printCorners(p, q, 2*sqrt(2));
return 0;
}
Output:
389
Chapter 67. Find Corners of Rectangle using mid points
0, 0
0, 2
2, 2
2, 0
0, 2
-2, 0
0, -2
2, 0
Reference:
StackOverflow
Source
https://www.geeksforgeeks.org/find-corners-of-rectangle-using-mid-points/
390
Chapter 68
Example:
Input: points[] = {(0, 3), (1, 1), (2, 2), (4, 4),
(0, 0), (1, 2), (3, 1}, {3, 3}};
We strongly recommend you to minimize your browser and try this yourself
first.
The idea is to use sorting.
1. Find the bottom-most point by comparing y coordinate of all points. If there are two
points with same y value, then the point with smaller x coordinate value is considered.
Put the bottom-most point at first position.
391
Chapter 68. Find Simple Closed Path for a given set of points
2. Consider the remaining n-1 points and sort them by polor angle in counterclockwise
order around points[0]. If polor angle of two points is same, then put the nearest point
first.
3. Traversing the sorted array (sorted in increasing order of angle) yields simple closed
path.
392
Chapter 68. Find Simple Closed Path for a given set of points
// A global point needed for sorting points with reference
// to the first point. Used in compare function of qsort()
Point p0;
// A utility function to swap two points
int swap(Point &p1, Point &p2)
{
Point temp = p1;
p1 = p2;
p2 = temp;
}
// A utility function to return square of distance between
// p1 and p2
int dist(Point p1, Point p2)
{
return (p1.x - p2.x)*(p1.x - p2.x) +
(p1.y - p2.y)*(p1.y - p2.y);
}
// To find orientation of ordered triplet (p, q, r).
// The function returns following values
// 0 --> p, q and r are colinear
// 1 --> Clockwise
// 2 --> Counterclockwise
int orientation(Point p, Point q, Point r)
{
int val = (q.y - p.y) * (r.x - q.x) -
(q.x - p.x) * (r.y - q.y);
if (val == 0) return 0; // colinear
return (val > 0)? 1: 2; // clockwise or counterclock wise
}
// A function used by library function qsort() to sort
// an array of points with respect to the first point
int compare(const void *vp1, const void *vp2)
{
Point *p1 = (Point *)vp1;
Point *p2 = (Point *)vp2;
// Find orientation
int o = orientation(p0, *p1, *p2);
if (o == 0)
return (dist(p0, *p2) >= dist(p0, *p1))? -1 : 1;
return (o == 2)? -1: 1;
393
Chapter 68. Find Simple Closed Path for a given set of points
}
// Prints simple closed path for a set of n points.
void printClosedPath(Point points[], int n)
{
// Find the bottommost point
int ymin = points[0].y, min = 0;
for (int i = 1; i < n; i++)
{
int y = points[i].y;
// Pick the bottom-most. In case of tie, chose the
// left most point
if ((y < ymin) || (ymin == y &&
points[i].x < points[min].x))
ymin = points[i].y, min = i;
}
// Place the bottom-most point at first position
swap(points[0], points[min]);
// Sort n-1 points with respect to the first point.
// A point p1 comes before p2 in sorted ouput if p2
// has larger polar angle (in counterclockwise
// direction) than p1
p0 = points[0];
qsort(&points[1], n-1, sizeof(Point), compare);
// Now stack has the output points, print contents
// of stack
for (int i=0; i<n; i++)
cout << "(" << points[i].x << ", "
<< points[i].y <<"), ";
}
// Driver program to test above functions
int main()
{
Point points[] = {{0, 3}, {1, 1}, {2, 2}, {4, 4},
{0, 0}, {1, 2}, {3, 1}, {3, 3}};
int n = sizeof(points)/sizeof(points[0]);
printClosedPath(points, n);
return 0;
}
Output:
394
Chapter 68. Find Simple Closed Path for a given set of points
(0, 0), (3, 1), (1, 1), (2, 2), (3, 3),
(4, 4), (1, 2), (0, 3),
Time complexity of above solution is O(n Log n) if we use a O(nLogn) sorting algorithm for
sorting points.
Source:
http://www.dcs.gla.ac.uk/~pat/52233/slides/Geometry1x1.pdf
This article is contributed by Rajeev Agrawal. Please write comments if you find anything
incorrect, or you want to share more information about the topic discussed above
Source
https://www.geeksforgeeks.org/find-simple-closed-path-for-a-given-set-of-points/
395
Chapter 69
After re-arranging
396
Chapter 69. Find all angles of a given triangle
In trigonometry, the law of cosines (also known as the cosine formula or cosine rule) relates
the lengths of the sides of a triangle to the cosine of one of its angles.
C++
397
Chapter 69. Find all angles of a given triangle
Java
398
Chapter 69. Find all angles of a given triangle
static void printAngle(Point A, Point B,
Point C)
{
// Square of lengths be a2, b2, c2
int a2 = lengthSquare(B,C);
int b2 = lengthSquare(A,C);
int c2 = lengthSquare(A,B);
// lenght of sides be a, b, c
float a = (float)sqrt(a2);
float b = (float)sqrt(b2);
float c = (float)sqrt(c2);
// From Cosine law
float alpha = (float) acos((b2 + c2 - a2)/(2*b*c));
float betta = (float) acos((a2 + c2 - b2)/(2*a*c));
float gamma = (float) acos((a2 + b2 - c2)/(2*a*b));
// Converting to degree
alpha = (float) (alpha * 180 / PI);
betta = (float) (betta * 180 / PI);
gamma = (float) (gamma * 180 / PI);
// printing all the angles
System.out.println("alpha : " + alpha);
System.out.println("betta : " + betta);
System.out.println("gamma : " + gamma);
}
// Driver method
public static void main(String[] args)
{
Point A = new Point(0,0);
Point B = new Point(0,1);
Point C = new Point(1,0);
printAngle(A,B,C);
}
}
Output:
alpha : 90
betta : 45
gamma : 45
399
Chapter 69. Find all angles of a given triangle
Reference :
https://en.wikipedia.org/wiki/Law_of_cosines
Source
https://www.geeksforgeeks.org/find-angles-given-triangle/
400
Chapter 70
Input:
x1 = -1, y1 = 3, z1 = 2
x2 = 2, y2 = 3, z2 = 5
x3 = 3, y3 = 5, z3 = -2
Output:
angle A = 90.0 degree
angle B = 54.736 degree
angle C = 35.264 degree
401
Chapter 70. Find all angles of a triangle in 3D
Approach:
For finding angle A find out direction ratios of AB and AC :
direction ratios of AB = x2-x1, y2-y1, z2-z1
direction ratios of AC = x3-x1, y3-y1, z3-z1
then angle A =
For finding angle B find out direction ratios of BA and BC :
direction ratios of BA = x1-x2, y1-y2, z1-z2
direction ratios of BC = x3-x2, y3-y2, z3-z2
then angle B =
For finding angle C find out direction ratios of CB and CA :
402
Chapter 70. Find all angles of a triangle in 3D
then angle C =
Below is the implementation of above approach:
Output:
Angles are :
angle A = 90.0 degree
angle B = 54.736 degree
angle C = 35.264 degree
403
Chapter 70. Find all angles of a triangle in 3D
Source
https://www.geeksforgeeks.org/find-all-angles-of-a-triangle-in-3d/
Please write to us at [email protected] to report any issue with the above con-
tent.
404
Chapter 71
Hence, we can say that only 3 coordinates are possible from which we can generate a
parallelogram if three coordinates are given.
To prove that all the three points are different let’s suppose it’s wrong. Without losing of
generality suppose that the points got in cases AD and BC are equal.
Consider the system of two equations for the equality of these points:
Bx + Cx - Ax = Ax + Cx - Bx
By + Cy - Ay = Ay + Cy - By
Ax = Bx
Ay = By
405
Chapter 71. Find all possible coordinates of parallelogram
Input : A = (0 0)
B = (1 0)
C = (0 1)
Output : 1 -1
-1 1
1 1
Since the opposite sides are equal, AD = BC and AB = CD, we can calculate the co-ordinates
of the missing point (D) as:
AD = BC
(Dx - Ax, Dy - Ay) = (Cx - Bx, Cy - By)
Dx = Ax + Cx - Bx
Dy = Ay + Cy - By
The cases where the diagonals are AD and BC, CD and AB are processed in the same way.
Reference: https://math.stackexchange.com/questions/1322535/how-many-different-parallelograms-can-be-drawn
Below is the implementation of above approach:
C++
406
Chapter 71. Find all possible coordinates of parallelogram
Java
Python3
407
Chapter 71. Find all possible coordinates of parallelogram
bx = 1
by = 1 #coordinates of B
cx = 2
cy = 5 #coordinates of C
print(ax + bx - cx, ", ", ay + by - cy)
print(ax + cx - bx, ", ", ay + cy - by)
print(cx + bx - ax, ", ", cy + by - ax)
C#
PHP
<?php
// PHP program to all
// possible points
// of a parallelogram
408
Chapter 71. Find all possible coordinates of parallelogram
// Driver Code
//coordinates of A
$ax = 5; $ay = 0;
//coordinates of B
$bx = 1; $by = 1;
//coordinates of C
$cx = 2; $cy = 5;
echo $ax + $bx - $cx , ", "
, $ay + $by - $cy ,"\n";
echo $ax + $cx - $bx , ", "
, $ay + $cy - $by,"\n" ;
echo $cx + $bx - $ax , ", "
, $cy + $by - $ax ;
// This code is contributed by anuj_67.
?>
Output:
4, -4
6, 4
-2, 1
Source
https://www.geeksforgeeks.org/find-possible-coordinates-parallelogram/
409
Chapter 72
Find all sides of a right angled triangle from given hypotenuse and area | Set 1 - Geeks-
forGeeks
Given hypotenuse and area of a right angle triangle, get its base and height and if any
triangle with given hypotenuse and area is not possible, print not possible.
Examples:
We can use a property of right angle triangle for solving this problem, which can be stated
as follows,
410
Chapter 72. Find all sides of a right angled triangle from given hypotenuse and area | Set 1
Now if given area is less than this maximum area, we can do a binary search for length of
base, as increasing base will increases area, it is a monotonically increasing function where
binary search can be applied easily.
In below code, a method is written for getting area of right angle triangle, recall that for right
angle triangle area is ½*base*height and height can be calculated from base and hypotenuse
using pythagorean theorem.
411
Chapter 72. Find all sides of a right angled triangle from given hypotenuse and area | Set 1
// if given area itself is larger than maxArea then no
// solution is possible
if (area > maxArea)
{
cout << "Not possiblen";
return;
}
double low = 0.0;
double high = sideForMaxArea;
double base;
// binary search for base
while (abs(high - low) > eps)
{
base = (low + high) / 2.0;
if (getArea(base, hypotenuse) >= area)
high = base;
else
low = base;
}
// get height by pythagorean rule
double height = sqrt(hsquare - base*base);
cout << base << " " << height << endl;
}
// Driver code to test above methods
int main()
{
int hypotenuse = 5;
int area = 6;
printRightAngleTriangle(hypotenuse, area);
return 0;
}
Output:
3 4
412
Chapter 72. Find all sides of a right angled triangle from given hypotenuse and area | Set 1
Source
https://www.geeksforgeeks.org/find-sides-right-angled-triangle-given-hypotenuse-area/
413
Chapter 73
Find an Integer point on a line segment with given two ends - GeeksforGeeks
Given two points pointU and pointV in XY-space, we need to find a point which has
integer coordinates and lies on a line going through points pointU and pointV.
Examples:
We can see that once we found the equation of line, this problem can be treated as Extended
Euclid algorithm problem, where we know A, B, C in AX + BY = C and we want to find
out the value of X and Y from the equation.
In above Extended Euclid equation, C is gcd of A and B, so after finding out the line
equation from given two points if C is not a multiple of gcd(A, B) then we can conclude
that there is no possible integer coordinate on the specified line. If C is a multiple of g, then
we can scale up the founded X and Y coefficients to satisfy the actual equation, which will
be our final answer.
414
Chapter 73. Find an Integer point on a line segment with given two ends
{
// Base Case
if (a == 0)
{
*x = 0;
*y = 1;
return b;
}
int x1, y1; // To store results of recursive call
int gcd = gcdExtended(b%a, a, &x1, &y1);
// Update x and y using results of recursive
// call
*x = y1 - (b/a) * x1;
*y = x1;
return gcd;
}
// method prints integer point on a line with two
// points U and V.
void printIntegerPoint(int c[], int pointV[])
{
// Getting coefficient of line
int A = (pointU[1] - pointV[1]);
int B = (pointV[0] - pointU[0]);
int C = (pointU[0] * (pointU[1] - pointV[1]) +
pointU[1] * (pointV[0] - pointU[0]));
int x, y; // To be assigned a value by gcdExtended()
int g = gcdExtended(A, B, &x, &y);
// if C is not divisble by g, then no solution
// is available
if (C % g != 0)
cout << "No possible integer point\n";
else
// scaling up x and y to satisfy actual answer
cout << "Integer Point : " << (x * C/g) << " "
<< (y * C/g) << endl;
}
// Driver code to test above methods
int main()
{
415
Chapter 73. Find an Integer point on a line segment with given two ends
Output:
Integer Point : 6 -3
Source
https://www.geeksforgeeks.org/find-integer-point-line-segment-given-two-ends/
416
Chapter 74
Find area of parallelogram if vectors of two adjacent sides are given - GeeksforGeeks
Given two vectors in form of (xi+yj+zk) of two adjacent sides of a parallelogram. The task
is to find out the area of a parallelogram.
Example:
Input:
x1 = 3, y1 = 1, z1 = -2
x2 = 1, y2 = -3, z2 = 4
Output: Area = 17.3205081
Input:
x1 = 1, y1 = 3, z1 = 2
x2 = 1, y2 = -3, z2 = 4
Output: Area = 19.078784028338912
417
Chapter 74. Find area of parallelogram if vectors of two adjacent sides are given
Python Code:
418
Chapter 74. Find area of parallelogram if vectors of two adjacent sides are given
x2 = 1
y2 = -3
z2 = 4
a = area(x1, y1, z1, x2, y2, z2)
print("Area = ", a)
# driver code
if __name__=="__main__":
main()
Output:
Area = 17.320508075688775
Source
https://www.geeksforgeeks.org/find-area-of-parallelogram-if-vectors-of-two-adjacent-sides-are-given/
419
Chapter 75
Input : a1 = 0, a2 = 1, b1 = 1, b2 = 1,
c1 = 1, c2 = 0
Output : Yes
Explanation : Rotate the page by 90 degree.
Input : a1 = 1, a2 = 1, b1 = 0, b2 = 0,
c1 = 1000, c2 = 1000
Output : No
Rotation of page by some angle is only possible if the distance between points ‘a’ and ‘b’ is
equal to distance between points ‘b’ and ‘c’. But if the points are on same line, there is no
rotation at point ‘b’. The problem has no solution when ‘a’, ‘b’, ‘c’ are in the same line or
dis(a, b) != dis(b, c)
C++
420
Chapter 75. Find if it’s possible to rotate the page by an angle or not.
Java
421
Chapter 75. Find if it’s possible to rotate the page by an angle or not.
Python3
422
Chapter 75. Find if it’s possible to rotate the page by an angle or not.
C#
423
Chapter 75. Find if it’s possible to rotate the page by an angle or not.
Console.Write("No");
// If the points are in same line
else if (b1 == ((a1 + c1) / 2.0) && b2 ==
((a2 + c2) / 2.0))
Console.Write("No");
else
Console.Write("Yes");
}
// Driver method
public static void Main()
{
// Points a, b, and c
long a1 = 1, a2 = 0, b1 = 2,
b2 = 0, c1 = 3, c2 = 0;
possibleOrNot(a1, a2, b1, b2, c1, c2);
}
}
// This code is contributed by Anant Agarwal.
PHP
<?php
// PHP program to fill
// an array with frequencies.
// function to find if
// it's possible to
// rotate page or not
function possibleOrNot($a1, $a2, $b1,
$b2, $c1, $c2)
{
// Calulating distance
// b/w points
$dis1 = pow($b1 - $a1, 2) +
pow($b2 - $a2, 2);
$dis2 = pow($c1 - $b1, 2) +
pow($c2 - $b2, 2);
// If distance
// is not equal
if($dis1 != $dis2)
echo "No";
// If the points
// are in same line
424
Chapter 75. Find if it’s possible to rotate the page by an angle or not.
Output:
No
Improved By : jit_t
Source
https://www.geeksforgeeks.org/find-possible-rotate-page-angle-not/
425
Chapter 76
We need to write a function bool doOverlap(l1, r1, l2, r2) that returns true if the two given
rectangles overlap.
Note : It may be assumed that the rectangles are parallel to the coordinate axis.
One solution is to one by one pick all points of one rectangle and see if the point lies inside
the other rectangle or not. This can be done using the algorithm discussed here.
Following is a simpler approach. Two rectangles do not overlap if one of the following
conditions is true.
1) One rectangle is above top edge of other rectangle.
2) One rectangle is on left side of left edge of other rectangle.
426
Chapter 76. Find if two rectangles overlap
We need to check above cases to find out if given rectangles overlap or not. Following is
C++ implementation of the above approach.
#include<bits/stdc++.h>
struct Point
{
int x, y;
};
// Returns true if two rectangles (l1, r1) and (l2, r2) overlap
bool doOverlap(Point l1, Point r1, Point l2, Point r2)
{
// If one rectangle is on left side of other
if (l1.x > r2.x || l2.x > r1.x)
return false;
// If one rectangle is above other
if (l1.y < r2.y || l2.y < r1.y)
return false;
return true;
}
/* Driver program to test above function */
int main()
{
Point l1 = {0, 10}, r1 = {10, 0};
Point l2 = {5, 5}, r2 = {15, 0};
if (doOverlap(l1, r1, l2, r2))
printf("Rectangles Overlap");
else
printf("Rectangles Don't Overlap");
return 0;
}
Output:
Rectangles Overlap
Time Complexity of above code is O(1) as the code doesn’t have any loop or recursion.
This article is compiled by Aman Gupta. Please write comments if you find anything
incorrect, or you want to share more information about the topic discussed above
Source
https://www.geeksforgeeks.org/find-two-rectangles-overlap/
427
Chapter 77
We can solve this problem using sorting. First, we will calculate intersection point of each
line with both the boundaries of vertical section and store that as a pair. We just need to
store y-coordinates of intersections as a pair because x-coordinates are equal to boundary
itself. Now we will sort these pairs on the basis of their intersection with left boundary.
After that, we will loop over these pairs one by one and if for any two consecutive pairs, the
second value of the current pair is less than that of the second value of the previous pair
then there must be an intersection in the given vertical section.
The possible orientation of two consecutive pairs can be seen in above diagram for L1 and
L2. We can see that when the second value is less, intersection lies in vertical section.
Total time complexity of solution will be O(n logn)
428
Chapter 77. Find intersection point of lines inside a section
429
Chapter 77. Find intersection point of lines inside a section
// Driver code to test above methods
int main()
{
int N = 4;
int m[] = { 1, -1, 0, 2 };
int b[] = { 2, 7, -3, -7 };
// copy values in line struct
line lines[N];
for (int i = 0; i < N; i++) {
lines[i] = line(m[i], b[i]);
int xL = 2;
int xR = 4;
if (isIntersectionPointInsideSection(lines, xL, xR, N)) {
cout << "Intersection point lies between "
<< xL << " and " << xR << endl;
} else {
cout << "No Intersection point lies between "
<< xL << " and " << xR << endl;
}
}
Output:
Source
https://www.geeksforgeeks.org/find-intersection-point-lines-inside-section/
430
Chapter 78
As we all know about the properties of magnet that they repel each other when they are
facing each other with the same pole and attract each other when they are facing each other
with opposite pole. Also, the force of attraction, as well as repulsion, always work in a
straight line.
We have two pivots points on coordinates, so distance between these points are D = ((x1-
x2)2 +(y1-y2)2 )1/2 .
Also, we can conclude that distance between magnet is maximum while repulsion and that
too should be the distance between pivots + sum of the length of both strings.
In case of attraction we have two cases to take care of:
Either the minimum distance is the distance between pivots – the sum of the length of both
strings
Or minimum distance should be zero in case if the sum of the length of strings is greater
than the distance between pivot points.
431
Chapter 78. Find maximum and minimum distance between magnets
C++
432
Chapter 78. Find maximum and minimum distance between magnets
Java
433
Chapter 78. Find maximum and minimum distance between magnets
// Driver Code
public static void main (String[] args)
{
int x0 = 0, y0 = 0, x1 = 8,
y1 = 0, r1 = 4, r2 = 5;
int D = pivotDis(x0, y0, x1, y1);
System.out.print( "Distance while " +
"repulsion = " +
maxDis(D, r1, r2));
System.out.print("\nDistance while " +
"attraction = " +
minDis(D, r1, r2));
}
}
// This code is contributed by anuj_67.
Python3
434
Chapter 78. Find maximum and minimum distance between magnets
C#
435
Chapter 78. Find maximum and minimum distance between magnets
PHP
<?php
// PHP program for max and
// min distance
// Function for finding
// distance between pivots
function pivotDis($x0, $y0,
$x1, $y1)
{
return sqrt(($x1 - $x0) *
($x1 - $x0) +
($y1 - $y0) *
($y1 - $y0));
}
// Function for minimum distance
function minDis( $D, $r1, $r2)
{
return max(($D - $r1 - $r2), 0);
}
// Function for maximum distance
function maxDis( $D, $r1, $r2)
{
return $D + $r1 + $r2;
}
// Driver code
$x0 = 0; $y0 = 0;
$x1 = 8; $y1 = 0;
$r1 = 4; $r2 = 5;
$D = pivotDis($x0, $y0,
$x1, $y1);
echo "Distance while repulsion = "
, maxDis($D, $r1, $r2);
436
Chapter 78. Find maximum and minimum distance between magnets
Output:
Source
https://www.geeksforgeeks.org/find-maximum-minimum-distance-magnets/
437
Chapter 79
Find minimum radius such that atleast k point lie inside the circle - GeeksforGeeks
Given a positive integer K, a circle center at (0, 0) and coordinates of some points. The task
is to find minimum radius of the circle so that at-least k points lie inside the circle. Output
the square of the minimum radius.
Examples:
The idea is to find square of Euclidean Distance of each point from origin (0, 0). Now, sort
these distance in increasing order. Now the kth element of distance is the required minimum
radius.
438
Chapter 79. Find minimum radius such that atleast k point lie inside the circle
C++
Java
439
Chapter 79. Find minimum radius such that atleast k point lie inside the circle
class GFG
{
// Return minumum distance required so that
// aleast k point lie inside the circle.
static int minRadius(int k, int[] x, int[] y,
int n)
{
int[] dis=new int[n];
// Finding distance between of each
// point from origin
for (int i = 0; i < n; i++)
dis[i] = x[i] * x[i] + y[i] * y[i];
// Sorting the distance
Arrays.sort(dis);
return dis[k - 1];
}
// Driven Program
public static void main (String[] args) {
int k = 3;
int[] x = { 1, -1, 1 };
int[] y = { 1, -1, -1 };
int n = x.length;
System.out.println(minRadius(k, x, y, n));
}
}
/* This code is contributed by Mr. Somesh Awasthi */
Python3
440
Chapter 79. Find minimum radius such that atleast k point lie inside the circle
# Finding distance between of each
# point from origin
for i in range(0, n):
dis[i] = x[i] * x[i] + y[i] * y[i]
# Sorting the distance
dis.sort()
return dis[k - 1]
# Driver Program
k = 3
x = [1, -1, 1]
y = [1, -1, -1]
n = len(x)
print(minRadius(k, x, y, n))
# This code is contributed by
# Prasad Kshirsagar
C#
441
Chapter 79. Find minimum radius such that atleast k point lie inside the circle
return dis[k - 1];
}
// Driven Program
public static void Main ()
{
int k = 3;
int[] x = { 1, -1, 1 };
int[] y = { 1, -1, -1 };
int n = x.Length;
Console.WriteLine(
minRadius(k, x, y, n));
}
}
// This code is contributed by vt_m.
PHP
<?php
// PHP program to find minimum radius
// such that atleast k point lie inside
// the circle
// Return minumum distance required
// so that aleast k point lie
// inside the circle.
function minRadius($k, $x, $y, $n)
{
$dis =array();
// Finding distance between
// of each point from origin
for ($i = 0; $i < $n; $i++)
$dis[$i] = $x[$i] * $x[$i] +
$y[$i] * $y[$i];
// Sorting the distance
sort($dis);
return $dis[$k - 1];
}
// Driver Code
$k = 3;
$x = array(1, -1, 1);
442
Chapter 79. Find minimum radius such that atleast k point lie inside the circle
Output:
Source
https://www.geeksforgeeks.org/find-minimum-radius-atleast-k-point-lie-inside-circle/
443
Chapter 80
444
Chapter 80. Find mirror image of a point in 2-D plane
Since object and image are equidistant from mirror, R must be middle point of P and Q
Since equation of mirror is given to be: ax + by + c = 0. Equation of line passing through
P and Q is perpendicular to mirror. Therefore equation of line passing through P and Q
becomes ay – bx + d = 0, Also P passes through line passing through P and Q, so we put
coordinate of P in above equation,
a*y1 – b*x1 + d = 0
d = b*x1 – a*y1
Also R is intersection of mirror and line passing through P and Q. So we find solution of
ax + by + c = 0
ay -bx + d = 0
Since a, b, c, d all are known we can find x and y here. Since coordinates of R is known
now ie.. x3, y3 are known now.
Since R is middle point of PQ,
(x3, y3) = ((x1+x2)/2, (y1+y2)/2)
Since x1, y1, x3, y3 are known, we get below equation where (x, y) are coordinates of
Q(image point)
445
Chapter 80. Find mirror image of a point in 2-D plane
We use above formula to find mirror image of point P(x1, y1) with respect to mirror of
equation ax + by + c
Output:
446
Chapter 80. Find mirror image of a point in 2-D plane
Source
https://www.geeksforgeeks.org/find-mirror-image-point-2-d-plane/
447
Chapter 81
Input : 5
Output : 5
448
Chapter 81. Find number of diagonals in n sided convex polygon
Since for an n-sided convex polygon, from each vertex, we can draw n-3 diagonals leaving
two adjacent vertices and itself. Following this way for n-vertices, there will be n*(n-3)
diagonals but then we will be calculating each diagonal twice so total number of diagonals
become n*(n-3)/2
Here is code for above formula.
C++
#include <iostream>
using namespace std;
// C++ function to find number of diagonals
// in n sided convex polygon
449
Chapter 81. Find number of diagonals in n sided convex polygon
int numberOfDiagonals(int n)
{
return n * (n - 3) / 2;
}
// driver code to test above function
int main()
{
int n = 5;
cout << n << " sided convex polygon have ";
cout << numberOfDiagonals(n) << " diagonals";
return 0;
}
Java
C#
450
Chapter 81. Find number of diagonals in n sided convex polygon
return n * (n - 3) / 2;
}
// driver code to test above function
public static void Main()
{
int n = 5;
Console.Write(n + " sided convex polygon have ");
Console.WriteLine(numberOfDiagonals(n) +
" diagonals");
}
}
// This code is contributed by Sam007
PHP
<?php
// PHP function to find number
// of diagonals in n sided
// convex polygon
function numberOfDiagonals($n)
{
return $n * ($n - 3) / 2;
}
// Driver Code
$n = 5;
echo $n , " sided convex polygon have ";
echo numberOfDiagonals($n) ,
" diagonals";
// This code is contributed by aj_36
?>
Output :
Source
https://www.geeksforgeeks.org/find-number-diagonals-n-sided-convex-polygon/
451
Chapter 82
| 1 | | 1 1 |
Examples:
Input : mat[][] =
{
1, 0,
1, 1,
}
Output : 8
Cell (1,0) and (1,1) making a L shape whose perimeter is 8.
Input : mat[][] =
{
0, 1, 0, 0, 0,
1, 1, 1, 0, 0,
1, 0, 0, 0, 0
}
Output : 12
452
Chapter 82. Find perimeter of shapes formed with 1s in binary matrix
The idea is to traverse the matrix, find all ones and find their contribution in perimeter.
The maximum contribution of a 1 is four if it is surrounded by all 0s. The contribution
reduces by one with 1 around it.
Algorithm for solving this problem:
1. Traverse the whole matrix and find the cell having value equal to 1.
2. Calculate the number of closed side for that cell and add, 4 – number of closed side
to the total perimeter.
453
Chapter 82. Find perimeter of shapes formed with 1s in binary matrix
int perimeter = 0;
// Traversing the matrix and finding ones to
// calculate their contribution.
for (int i = 0; i < R; i++)
for (int j = 0; j < C; j++)
if (mat[i][j])
perimeter += (4 - numofneighbour(mat, i ,j));
return perimeter;
}
// Driven Program
int main()
{
int mat[R][C] =
{
0, 1, 0, 0, 0,
1, 1, 1, 0, 0,
1, 0, 0, 0, 0,
};
cout << findperimeter(mat) << endl;
return 0;
}
Java
454
Chapter 82. Find perimeter of shapes formed with 1s in binary matrix
// LEFT
if (j > 0 && mat[i][j - 1] == 1)
count++;
// DOWN
if (i < R - 1 && mat[i + 1][j] == 1)
count++;
// RIGHT
if (j < C - 1 && mat[i][j + 1] == 1)
count++;
return count;
}
// Returns sum of perimeter of shapes
// formed with 1s
static int findperimeter(int mat[][])
{
int perimeter = 0;
// Traversing the matrix and
// finding ones to calculate
// their contribution.
for (int i = 0; i < R; i++)
for (int j = 0; j < C; j++)
if (mat[i][j] == 1)
perimeter += (4 -
numofneighbour(mat, i, j));
return perimeter;
}
// Driver code
public static void main(String[] args)
{
int mat[][] = {{0, 1, 0, 0, 0},
{1, 1, 1, 0, 0},
{1, 0, 0, 0, 0}};
System.out.println(findperimeter(mat));
}
}
// This code is contributed by Anant Agarwal.
455
Chapter 82. Find perimeter of shapes formed with 1s in binary matrix
Output:
12
Source
https://www.geeksforgeeks.org/find-perimeter-shapes-formed-1s-binary-matrix/
456
Chapter 83
Input : p = (2, 1)
L = sqrt(2)
M = 1
Output :3, 2
1, 0
Explanation:
The two points are sqrt(2) distance away
from the source and have the required slope
m = 1.
Input : p = (1, 0)
L = 5
M = 0
Output : 6, 0
-4, 0
We need to find two points that are L distance from given point, on a line with slope M.
The idea has been introduced in below post.
Find Corners of Rectangle using mid points
Based on the input slope, the problem can be classified into 3 categories.
457
Chapter 83. Find points at a given distance on a line of given slope
1. If slope is zero, we just need to adjust the x coordinate of the source point
2. If slope is infinite, the we need to adjust the y coordinate
3. For other values of slope, we can use the following equations to find the points
Now using the above formula we can find the required points.
458
Chapter 83. Find points at a given distance on a line of given slope
b.y = source.y;
}
// if slope is infinte
else if (m == std::numeric_limits<float>
::max()) {
a.x = source.x;
a.y = source.y + l;
b.x = source.x;
b.y = source.y - l;
}
else {
float dx = (l / sqrt(1 + (m * m)));
float dy = m * dx;
a.x = source.x + dx;
a.y = source.y + dy;
b.x = source.x - dx;
b.y = source.y - dy;
}
// print the first Point
cout << a.x << ", " << a.y << endl;
// print the second Point
cout << b.x << ", " << b.y << endl;
}
// driver function
int main()
{
Point p(2, 1), q(1, 0);
printPoints(p, sqrt(2), 1);
cout << endl;
printPoints(q, 5, 0);
return 0;
}
Output:
3, 2
1, 0
6, 0
-4, 0
459
Chapter 83. Find points at a given distance on a line of given slope
Source
https://www.geeksforgeeks.org/find-points-at-a-given-distance-on-a-line-of-given-slope/
460
Chapter 84
Input : A = (1, 0)
B = (1, 1)
C = (0, 1)
Output : 0, 0
Explanation:
The three input points form a unit
square with the point (0, 0)
Input : A = (5, 0)
B = (1, 1)
C = (2, 5)
Output : 6, 4
As shown in below diagram, there can be multiple possible outputs, we need to print any
one of them.
461
Chapter 84. Find the Missing Point of Parallelogram
A quadrilateral is said to be a parallelogram if its opposite sides are parallel and equal in
length.
As we’re given three points of the parallelogram, we can find the slope of the missing sides
as well as their lengths.
The algorithm can be explained as follows
Let R be the missing point. Now from definition, we have
462
Chapter 84. Find the Missing Point of Parallelogram
Thus we can find the points at a distance L1 from P having slope M1 as mentioned in below
article :
Find points at a given distance on a line of given slope.
Now one of the points will satisfy the above conditions which can easily be checked (using
either condition 3 or 4).
Below is the program for the same.
C++
463
Chapter 84. Find the Missing Point of Parallelogram
464
Chapter 84. Find the Missing Point of Parallelogram
Output :
0, 0
6, 4
Alternative Approach:
Since the opposite sides are equal, AD = BC and AB = CD, we can calculate the co-ordinates
of the missing point (D) as:
AD = BC
(Dx - Ax, Dy - Ay) = (Cx - Bx, Cy - By)
Dx = Ax + Cx - Bx
Dy = Ay + Cy - By
References: https://math.stackexchange.com/questions/887095/find-the-4th-vertex-of-the-parallelogram
465
Chapter 84. Find the Missing Point of Parallelogram
Java
Python 3
466
Chapter 84. Find the Missing Point of Parallelogram
# Main method
if __name__ == "__main__":
# coordinates of A
ax, ay = 5, 0
# coordinates of B
bx ,by = 1, 1
# coordinates of C
cx ,cy = 2, 5
print(ax + cx - bx , ",", ay + cy - by)
# This code is contributed by Smitha
C#
// C# program to
// find missing point
// of a parallelogram
using System;
class GFG
{
static public void Main ()
{
int ax = 5, ay = 0; //coordinates of A
int bx = 1, by = 1; //coordinates of B
int cx = 2, cy = 5; //coordinates of C
Console.WriteLine(ax + (cx - bx) + ", " +
ay + (cy - by));
}
}
// This code is contributed by ajit
PHP
<?php
// PHP program to find missing
// point of a parallelogram
// Driver Code
467
Chapter 84. Find the Missing Point of Parallelogram
$ax = 5;
$ay = 0; //coordinates of A
$bx = 1;
$by = 1; //coordinates of B
$cx = 2;
$cy = 5; //coordinates of C
echo $ax + $cx - $bx , ", ",
$ay + $cy - $by;
// This code is contributed by aj_36
?>
Output:
6, 4
Source
https://www.geeksforgeeks.org/find-missing-point-parallelogram/
468
Chapter 85
Given a N*M matrix A[][] representing a 3D figure. The height of the building at
Explanation :
The total surface area is 6 i.e 6 side of
the figure and each are of height 1.
Approach : To find the surface area we need to consider the contribution of all the six
sides of the given 3D figure. We will solve the questions in part to make it easy. The base of
the Figure will always contribute N*M to the total surface area of the figure, and same N*M
area will be contributed by the top of the figure. Now, to calculate the area contributed by
the walls, we will take out the absolute difference between the height of two adjacent wall.
The difference will be the contribution in the total surface area.
Below is the implementation of the above idea :
469
Chapter 85. Find the Surface area of a 3D figure
C++
470
Chapter 85. Find the Surface area of a 3D figure
/* If its the rightmost block of the matrix
it will contribute area equal to its height
as a wall on the right of the figure */
if (i == N - 1)
ans += A[i][j];
/* If its the lowest block of the matrix it will
contribute area equal to its height as a wall
on the bottom of the figure */
if (j == M - 1)
ans += A[i][j];
}
}
// Adding the contribution by the base and top of the figure
ans += N * M * 2;
return ans;
}
// Driver program
int main()
{
int A[N][M] = { { 1, 3, 4 },
{ 2, 2, 3 },
{ 1, 2, 4 } };
cout << surfaceArea(A) << endl;
return 0;
}
Java
471
Chapter 85. Find the Surface area of a 3D figure
472
Chapter 85. Find the Surface area of a 3D figure
}
// Adding the contribution by
// the base and top of the figure
ans += N * M * 2;
return ans;
}
// Driver code
public static void main (String[] args)
{
int A[][] = {{ 1, 3, 4 },
{ 2, 2, 3 },
{ 1, 2, 4 } };
System.out.println(surfaceArea(A));
}
}
// This code is contributed By Anant Agarwal.
C#
473
Chapter 85. Find the Surface area of a 3D figure
474
Chapter 85. Find the Surface area of a 3D figure
// Driver code
public static void Main ()
{
int [,]A = {{ 1, 3, 4 },
{ 2, 2, 3 },
{ 1, 2, 4 } };
Console.WriteLine(surfaceArea(A));
}
}
// This code is contributed By vt_m.
PHP
<?php
// PHP program to find the
// Surface area of a 3D figure
// Declaring the size
// of the matrix
$M = 3;
$N = 3;
// Absolute Difference
// between the height of
// two consecutive blocks
function contribution_height($current,
$previous)
{
return abs($current - $previous);
}
// Function To calculate
// the Total surfaceArea.
function surfaceArea($A)
{
global $M;
global $N;
$ans = 0;
// Traversing the matrix.
for ($i = 0; $i < $N; $i++)
{
for ($j = 0; $j < $M; $j++)
{
475
Chapter 85. Find the Surface area of a 3D figure
476
Chapter 85. Find the Surface area of a 3D figure
$ans += $N * $M * 2;
return $ans;
}
// Driver Code
$A = array(array(1, 3, 4),
array(2, 2, 3),
array(1, 2, 4));
echo surfaceArea($A);
// This code is contributed By mits
?>
Output :
60
Source
https://www.geeksforgeeks.org/find-surface-area-3d-figure/
477
Chapter 86
Input : x1 = 5, y1 = 3 and
x2 = –10 y2 = 4
Output : –2.5, 3.5
Midpoint Formula:
The midpoint of two points, (x1, y2) and (x2, y2) is : M = ((x 1 + x 2 ) / 2, (y 1 +y
2 ) / 2)
The center of the circle is the mid point of its diameter so we calculate the mid point of its
diameter by using midpoint formula.
478
Chapter 86. Find the center of the circle using endpoints of diameter
479
Chapter 86. Find the center of the circle using endpoints of diameter
C++
Java
480
Chapter 86. Find the center of the circle using endpoints of diameter
}
}
// This code is contributed by Anant Agarwal.
Python3
C#
481
Chapter 86. Find the center of the circle using endpoints of diameter
}
// This code is contributed by vt_m.
PHP
<?php
// PHP program to find the
// center of the circle
// function to find the
// center of the circle
function center($x1, $x2, $y1, $y2)
{
echo((float)($x1 + $x2) / 2 . ", " .
(float)($y1 + $y2) / 2);
}
// Driven Code
$x1 = -9; $y1 = 3; $x2 = 5; $y2 = -7;
center($x1, $x2, $y1, $y2);
// This code is contributed by Ajit.
?>
Output :
-2, -2
Improved By : jit_t
Source
https://www.geeksforgeeks.org/find-center-circle-using-endpoints-diameter/
482
Chapter 87
Input : H = 10, A = 24
Output : P = 6.00, B = 8.00
Input : H = 13, A = 36
Output : Not Possible
Approach:
Before moving to exact solution, let’s do some of mathematical calculations related to prop-
erties of Right angled triangle.
Suppose H = Hypotenuse, P = Perpendicular, B = Base and A = Area of right angled
triangle.
We have some sort of equations as :
483
Chapter 87. Find the dimensions of Right angled triangle
C++
484
Chapter 87. Find the dimensions of Right angled triangle
int A = 6;
findDimen(H, A);
return 0;
}
Java
Python3
485
Chapter 87. Find the dimensions of Right angled triangle
C#
486
Chapter 87. Find the dimensions of Right angled triangle
PHP
<?php
// PHP program to find dimensions
// of Right angled triangle
// function to calculate dimension
function findDimen($H, $A)
{
// P^2+B^2 = H^2
// P*B = 2*A
// (P+B)^2 = P^2+B^2+2*P*B = H^2+4*A
// (P-B)^2 = P^2+B^2-2*P*B = H^2-4*A
487
Chapter 87. Find the dimensions of Right angled triangle
Output:
P = 3.00
B = 4.00
Improved By : vt_m
Source
https://www.geeksforgeeks.org/find-dimensions-right-angled-triangle/
488
Chapter 88
Find the other end point of a line with given one end and mid - GeeksforGeeks
Given a midpoint of line(m1, m2) and one coordinate of a line (x1, y1), find the other end
point(x2, y2) of a line
Examples:
The Midpoint Formula: The midpoint of two points, (x1, y2) and (x2, y2) is the point M
489
Chapter 88. Find the other end point of a line with given one end and mid
found by using:
M=((x1+x2)/2, (y1+y2)/2),
We have need of a (x2, y2) so we modifies the formula
m1 = ((x1+x2)/2), m2 = ((y1+y2)/2)
2*m1 = (x1+x2), 2*m2 = (y1+y2)
x2 = (2*m1 - x1), y2 = (2*m2 - y1)
C++
Java
490
Chapter 88. Find the other end point of a line with given one end and mid
// find end point for y cordinates
float y2 = (float)(2 * m2 - y1);
System.out.println("x2 = " + x2 + ", "
+ "y2 = " + y2);
}
// Driven Program
public static void main(String args[])
{
int x1 = -4, y1 = -1, m1 = 3, m2 = 5;
otherEndPoint(x1, y1, m1, m2);
}
}
// This code is contributed by JaideepPyne.
Python3
C#
491
Chapter 88. Find the other end point of a line with given one end and mid
PHP
<?php
// php program to find the end point of a line
// PHP function to find the end point of a line
function otherEndPoint($x1, $y1, $m1, $m2)
{
// find end point for x cordinates
$x2 = (2 * $m1 - $x1);
// find end point for y cordinates
$y2 = (2 * $m2 - $y1);
echo "x2 = " . $x2 . ", y2 = " . $y2 ;
492
Chapter 88. Find the other end point of a line with given one end and mid
}
// Driven Program
$x1 = -4; $y1 = -1; $m1 = 3; $m2 = 5;
otherEndPoint($x1, $y1, $m1, $m2);
// This code is contributed by nitin mittal.
?>
Output:
x2 = 10, y2 = 11
Source
https://www.geeksforgeeks.org/find-end-point-line-given-one-end-mid/
493
Chapter 89
Formula :
Perimeter of cylinder ( P ) =
here d is the diameter of the cylinder
h is the height of the cylinder
Examples :
494
Chapter 89. Find the perimeter of a cylinder
C++
Java
495
Chapter 89. Find the perimeter of a cylinder
Python
# Function to calculate
# the perimeter of a cylinder
def perimeter( diameter, height ) :
return 2 * ( diameter + height )
# Driver function
diameter = 5 ;
height = 10 ;
print ("Perimeter = ",
perimeter(diameter, height))
C#
PHP
496
Chapter 89. Find the perimeter of a cylinder
<?php
// PHP program to find
// perimeter of cylinder
// Function to calculate perimeter
function perimeter($diameter, $height)
{
return 2 * ($diameter + $height);
}
// Driver Code
$diameter = 5;
$height = 10;
echo("Perimeter = ");
echo(perimeter($diameter, $height));
echo(" units");
// This code is contributed by vt_m.
?>
Output :
Perimeter = 30 units
Source
https://www.geeksforgeeks.org/find-perimeter-cylinder/
497
Chapter 90
Finding Quadrant of a
Coordinate with respect to a
Circle
498
Chapter 90. Finding Quadrant of a Coordinate with respect to a Circle
Approach:
Let center be (x’, y’)
499
Chapter 90. Finding Quadrant of a Coordinate with respect to a Circle
C++
500
Chapter 90. Finding Quadrant of a Coordinate with respect to a Circle
Java
501
Chapter 90. Finding Quadrant of a Coordinate with respect to a Circle
// Outside circle
if (val > Math.pow(R, 2))
return -1;
// 1st quadrant
if (PX > X && PY >= Y)
return 1;
// 2nd quadrant
if (PX <= X && PY > Y)
return 2;
// 3rd quadrant
if (PX < X && PY <= Y)
return 3;
// 4th quadrant
if (PX >= X && PY < Y)
return 4;
return 0;
}
// Driver Code
public static void main (String[] args)
{
// Coordinates of centre
int X = 0, Y = 3;
// Radius of circle
int R = 2;
// Coordinates of the given point
int PX = 1, PY = 4;
int ans = getQuadrant(X, Y, R, PX, PY);
if (ans == -1)
System.out.println( "Lies Outside the circle");
else if (ans == 0)
System.out.println( "Coincides with centre");
else
System.out.println( ans +" Quadrant");
}
}
// This code is contributed by anuj_67.
502
Chapter 90. Finding Quadrant of a Coordinate with respect to a Circle
Python3
# Python3 Program to find the
# quadrant of a given coordinate
# w.rt. the centre of a circle
import math
# Thus function returns the
# quadrant number
def getQuadrant(X, Y, R, PX, PY):
# Coincides with center
if (PX == X and PY == Y):
return 0;
val = (math.pow((PX – X), 2) +
math.pow((PY – Y), 2));
# Outside circle
if (val > pow(R, 2)):
return -1;
# 1st quadrant
if (PX > X and PY >= Y):
return 1;
# 2nd quadrant
if (PX <= X and PY > Y):
return 2;
# 3rd quadrant
if (PX < X and PY <= Y): return 3; # 4th quadrant if (PX >= X and PY < Y): return
4; # Driver Code # Coordinates of centre X = 0; Y = 3; # Radius of circle R = 2; #
Coordinates of the given po PX = 1; PY = 4; ans = getQuadrant(X, Y, R, PX, PY); if (ans
== -1) : print(”Lies Outside the circle”); elif (ans == 0) : print(”Coincides with centre”);
else:print(ans, ”Quadrant”); # This code is contributed by mits [tabby title=”C#”]
503
Chapter 90. Finding Quadrant of a Coordinate with respect to a Circle
return 0;
int val = (int)Math.Pow((PX - X), 2)
+ (int)Math.Pow((PY - Y), 2);
// Outside circle
if (val > Math.Pow(R, 2))
return -1;
// 1st quadrant
if (PX > X && PY >= Y)
return 1;
// 2nd quadrant
if (PX <= X && PY > Y)
return 2;
// 3rd quadrant
if (PX < X && PY <= Y)
return 3;
// 4th quadrant
if (PX >= X && PY < Y)
return 4;
return 0;
}
// Driver Code
public static void Main ()
{
// Coordinates of centre
int X = 0, Y = 3;
// Radius of circle
int R = 2;
// Coordinates of the given point
int PX = 1, PY = 4;
int ans =
getQuadrant(X, Y, R, PX, PY);
if (ans == -1)
Console.WriteLine( "Lies Outside"
+ " the circle");
else if (ans == 0)
Console.WriteLine( "Coincides "
+ "with centre");
504
Chapter 90. Finding Quadrant of a Coordinate with respect to a Circle
else
Console.WriteLine( ans +
" Quadrant");
}
}
// This code is contributed by anuj_67.
PHP
<?php
// PHP Program to find the quadrant of
// a given coordinate with respect to the
// centre of a circle
// Thus function returns the
// quadrant number
function getQuadrant($X, $Y, $R,
$PX, $PY)
{
// Coincides with center
if ($PX == $X and $PY == $Y)
return 0;
$val = pow(($PX - $X), 2) +
pow(($PY - $Y), 2);
// Outside circle
if ($val > pow($R, 2))
return -1;
// 1st quadrant
if ($PX > $X and $PY >= $Y)
return 1;
// 2nd quadrant
if ($PX <= $X and $PY > $Y)
return 2;
// 3rd quadrant
if ($PX < $X and $PY <= $Y)
return 3;
// 4th quadrant
if ($PX >= $X and $PY < $Y)
return 4;
}
505
Chapter 90. Finding Quadrant of a Coordinate with respect to a Circle
// Driver Code
// Coordinates of centre
$X = 0; $Y = 3;
// Radius of circle
$R = 2;
// Coordinates of the given po$
$PX = 1;
$PY = 4;
$ans = getQuadrant($X, $Y, $R,
$PX, $PY);
if ($ans == -1)
echo "Lies Outside the circle" ;
else if ($ans == 0)
echo "Coincides with centre" ;
else
echo $ans , " Quadrant" ;
// This code is contributed by anuj_67.
?>
Output:
1 Quadrant
Source
https://www.geeksforgeeks.org/finding-quadrant-coordinate-respect-circle/
506
Chapter 91
507
Chapter 91. Finding the vertex, focus and directrix of a parabola
Input : 5 3 2
Output : Vertex:(-0.3, 1.55)
Focus: (-0.3, 1.6)
Directrix: y=-198
Consult the formula below for explanation.
This problem is a simple example of implementations of formulae. Given below are the
required set of formulae which will help us tackle the problem.
508
Chapter 91. Finding the vertex, focus and directrix of a parabola
C++
#include <iostream>
using namespace std;
// Function to calculate Vertex, Focus and Directrix
void parabola(float a, float b, float c)
{
cout << "Vertex: (" << (-b / (2 * a)) << ", "
<< (((4 * a * c) - (b * b)) / (4 * a))
<< ")" << endl;
cout << "Focus: (" << (-b / (2 * a)) << ", "
<< (((4 * a * c) - (b * b) + 1) / (4 * a))
<< ")" << endl;
cout << "Directrix: y="
<< c - ((b * b) + 1) * 4 * a << endl;
}
// Driver Function
int main()
{
float a = 5, b = 3, c = 2;
parabola(a, b, c);
return 0;
}
Java
509
Chapter 91. Finding the vertex, focus and directrix of a parabola
Python 3
C#
510
Chapter 91. Finding the vertex, focus and directrix of a parabola
PHP
<?php
// PHP program to Find the vertex,
// focus and directrix of a parabola
// Function to calculate Vertex,
// Focus and Directrix
function parabola($a, $b, $c)
{
echo "Vertex: (" , (-$b / (2 * $a)) , ", ",
511
Chapter 91. Finding the vertex, focus and directrix of a parabola
Output –
Vertex:(-0.3, 1.55)
Focus: (-0.3, 1.6)
Directrix: y=-198
Source
https://www.geeksforgeeks.org/finding-vertex-focus-directrix-parabola/
512
Chapter 92
Input :
X*X + Y*Y = 25
Output :
The area of circle centered at origin is : 78.55
Input :
X*X + Y*Y = 64
Output :
The area of circle centered at origin is : 201.088
C++
513
Chapter 92. Given equation of a circle as string, find area
#include <bits/stdc++.h>
#define PI 3.142
using namespace std;
// Function to find the area
double findArea(double radius)
{
return PI * pow(radius, 2);
}
// Function to return the value of radius
static double findradius(string str)
{
// Intialization
double radius = 0;
// For storing the value of R*R
string st = "";
// For counting the number of
// spaces in the string
int c = 0;
// calulate the length of the
int len = str.length();
// getting the value of R*R
// After = sign
for (int i = 0; i < len; i++) {
if (str[i] == '=') {
c = 1;
}
else if (c == 1 && str[i] != ' ') {
st = st + str[i];
}
}
// Converting the digits into integer
// Taking square root of that number
radius = (double)sqrt(stoi(st));
return radius;
}
int main()
{
514
Chapter 92. Given equation of a circle as string, find area
Java
515
Chapter 92. Given equation of a circle as string, find area
Python3
516
Chapter 92. Given equation of a circle as string, find area
#Intialization
radius = 0
# For storing the value of R*R
st = ""
# For counting the number of
# spaces in the string
c = 0
# calulate the length of the
Len = len(str)
# getting the value of R*R
# After = sign
for i in range(0, Len):
if (str[i] == '='):
c = 1
elif (c == 1 and str[i] != ' '):
st = st + str[i]
# Converting the digits into integer
# Taking square root of that number
radius = float(math.sqrt(float(st)))
return radius
# Static input for equation
# of circle
str = "X*X + Y*Y = 100"
# calling the Function
radius = findradius(str)
# Display the result
print( "The area of circle " ,
"centered at origin is : " ,
(findArea(radius)))
# This code is contributed by Sam007.
C#
517
Chapter 92. Given equation of a circle as string, find area
class GFG
{
// Function to find the area
static double findArea(double radius)
{
return Math.PI * Math.Pow(radius, 2);
}
// Function to return the value of radius
static double findradius(string str)
{
double radius = 0;
// For storing the value
// of radius * radius
String st = "";
// For counting the number
// of spaces in the string
int c = 0;
// calulate the length of the
int len = str.Length;
// getting the value of radius * radius
// After = sign
for (int i = 0; i < len; i++)
{
if (str[i] == '=')
{
c = 1;
}
else if (c == 1 && str[i] != ' ')
{
st = st + str[i];
}
}
// Converting the digits into integer
// Taking square root of that number
if (c == 1)
radius = (double)Math.Sqrt(
int.Parse(st));
return radius;
}
// Driver code
public static void Main()
518
Chapter 92. Given equation of a circle as string, find area
{
// Static input for equation of circle
string str = "X*X + Y*Y = 100";
// calling the Function
double radius = findradius(str);
// Display the result
Console.WriteLine("The area of circle" +
" centered at origin is : " +
System.Math.Round(findArea(radius),1));
}
}
// This code is contributed by Sam007
Output:
Improved By : Sam007
Source
https://www.geeksforgeeks.org/given-equation-circle-find-area-circle/
519
Chapter 93
520
Chapter 93. Given n line segments, find if any two segments intersect
sweepLineIntersection(Points[0..2n-1]):
1. Sort Points[] from left to right (according to x coordinate)
4. return False
Example:
Let us consider the following example taken from here. There are 5 line segments 1, 2, 3,
4 and 5. The dotted green lines show sweep lines.
521
Chapter 93. Given n line segments, find if any two segments intersect
Following are steps followed by the algorithm. All points from left to right are processed
one by one. We maintain a self-balancing binary search tree.
Left end point of line segment 1 is processed: 1 is inserted into the Tree. The tree contains
1. No intersection.
Left end point of line segment 2 is processed: Intersection of 1 and 2 is checked. 2 is
inserted into the Tree. No intersection. The tree contains 1, 2.
Left end point of line segment 3 is processed: Intersection of 3 with 1 is checked. No
intersection. 3 is inserted into the Tree. The tree contains 2, 1, 3.
Right end point of line segment 1 is processed: 1 is deleted from the Tree. Intersection of
2 and 3 is checked. Intersection of 2 and 3 is reported. The tree contains 2, 3. Note
that the above pseudocode returns at this point. We can continue from here to report all
intersection points.
Left end point of line segment 4 is processed: Intersections of line 4 with lines 2 and 3
are checked. No intersection. 4 is inserted into the Tree. The tree contains 2, 4, 3.
522
Chapter 93. Given n line segments, find if any two segments intersect
Source
https://www.geeksforgeeks.org/given-a-set-of-line-segments-find-if-any-two-segments-intersect/
523
Chapter 94
The haversine of the central angle (which is d/r) is calculated by the following formula:
where r is the radius of earth(6371 km), d is the distance between two points,
is latitude of the two points and is longitude of the two points respectively.
Solving d by applying the inverse haversine or by using the inverse sine function, we get:
or
524
Chapter 94. Haversine formula to find distance between two points on a sphere
The distance between Big Ben in London (51.5007° N, 0.1246° W) and The Statue of Liberty
in
New York (40.6892° N, 74.0445° W) is 5574.8 km. This is not the exact measurement
because the
formula assumes that the Earth is a perfect sphere when in fact it is an oblate spheroid.
Below is the implementation of the above formulae:
C++
525
Chapter 94. Haversine formula to find distance between two points on a sphere
Java
PHP
<?php
526
Chapter 94. Haversine formula to find distance between two points on a sphere
Output:
5574.840456848555 K.M.
527
Chapter 94. Haversine formula to find distance between two points on a sphere
Source
https://www.geeksforgeeks.org/haversine-formula-to-find-distance-between-two-points-on-a-sphere/
528
Chapter 95
Hendecagonal number
Input : 2
Output :11
Input :6
Output :141
529
Chapter 95. Hendecagonal number
C++
530
Chapter 95. Hendecagonal number
Java
Python3
531
Chapter 95. Hendecagonal number
C#
532
Chapter 95. Hendecagonal number
Console.Write(n +
"rd Hendecagonal number: ");
Console.WriteLine( hendecagonal_num(n));
n = 10;
Console.Write(n +
"th Hendecagonal number: ");
Console.WriteLine( hendecagonal_num(n));
}
}
// This code is contributed by aj_36
PHP
<?php
// PHP program to find nth
// Hendecagonal number
// Function to find
// Hendecagonal number
function hendecagonal_num($n)
{
// Formula to calculate nth
// Hendecagonal number
return (9 * $n * $n - 7 * $n) / 2;
}
// Driver Code
$n = 3;
echo $n , "th Hendecagonal number: ";
echo hendecagonal_num($n);
echo "\n";
$n = 10;
echo $n , "th Hendecagonal number: ";
echo hendecagonal_num($n);
// This code is contributed by m_kit
?>
Output :
533
Chapter 95. Hendecagonal number
Reference: https://en.wikipedia.org/wiki/Polygonal_number
Improved By : jit_t
Source
https://www.geeksforgeeks.org/hendecagonal-number/
534
Chapter 96
Heptadecagonal number
Input : 5
Output :155
Input :9
Output :549
535
Chapter 96. Heptadecagonal number
C++
Java
536
Chapter 96. Heptadecagonal number
Python3
C#
537
Chapter 96. Heptadecagonal number
{
return ((15 * n * n) -
13 * n) / 2;
}
// Driver Code
public static void Main ()
{
long n = 3;
Console.Write( n + "th Heptadecagonal"
+ " number : ");
Console.WriteLine( heptadecagonalNum(n));
n = 8;
Console.Write( n + "th Heptadecagonal"
+ " number : ");
Console.WriteLine( heptadecagonalNum(n));
}
}
// This code is contributed by anuj_67.
PHP
<?php
// PHP program to find Nth
// heptadecagonal number
// Function to calculate heptadecagonal
// number
function heptadecagonalNum( $n)
{
return ((15 * $n * $n) -
13 * $n) / 2;
}
// Driver Code
$n = 3;
echo $n , "th Heptadecagonal number : ";
echo heptadecagonalNum($n);
echo "\n";
$n = 8;
echo $n , "th Heptadecagonal number : ";
echo heptadecagonalNum($n);
// This code is contributed by anuj_67.
?>
538
Chapter 96. Heptadecagonal number
Output
Reference: https://en.wikipedia.org/wiki/Polygonal_number
Improved By : vt_m, jit_t
Source
https://www.geeksforgeeks.org/heptadecagonal-number/
539
Chapter 97
Heptagonal number
Input : 2
Output :7
Input :15
Output :540
540
Chapter 97. Heptagonal number
C++
Java
541
Chapter 97. Heptagonal number
int n = 2;
System.out.println(heptagonalNumber(n));
n = 15;
System.out.println(heptagonalNumber(n));
}
}
// This code is contributed by anuj_67.
Python3
C#
542
Chapter 97. Heptagonal number
}
// Driver Code
public static void Main ()
{
int n = 2;
Console.WriteLine(heptagonalNumber(n));
n = 15;
Console.WriteLine(heptagonalNumber(n));
}
}
// This code is contributed by anuj_67.
PHP
<?php
// PHP program to find the
// nth Heptagonal number
// Function to return Nth
// Heptagonal number
function heptagonalNumber($n)
{
return ((5 * $n * $n) -
(3 * $n)) / 2;
}
// Driver Code
$n = 2;
echo heptagonalNumber($n), "\n";
$n = 15;
echo heptagonalNumber($n);
// This code is contributed
// by anuj_67.
?>
Output :
7
540
Reference: https://en.wikipedia.org/wiki/Heptagonal_number
Improved By : vt_m, jit_t
543
Chapter 97. Heptagonal number
Source
https://www.geeksforgeeks.org/heptagonal-number/
544
Chapter 98
Hexadecagonal number
Input : 2
Output :16
Input :7
Output :301
545
Chapter 98. Hexadecagonal number
C++
Java
546
Chapter 98. Hexadecagonal number
{
long n = 5;
System.out.println( n + "th "
+ "Hexadecagonal number : "
+ hexadecagonalNum(n));
n = 9;
System.out.println( n + "th "
+ "Hexadecagonal number : "
+ hexadecagonalNum(n));
}
}
// This code contribued by anuj_67.
Python3
C#
547
Chapter 98. Hexadecagonal number
PHP
<?php
// PHP program to find Nth
// hexadecagon number
// Function to calculate
// hexadecagonal number
function hexadecagonalNum($n)
{
return ((14 * $n * $n) - 12 * $n) / 2;
}
// Driver Code
$n = 5;
echo $n , "th Hexadecagonal number : ";
echo hexadecagonalNum($n);
echo "\n";
$n = 9;
echo $n , "th Hexadecagonal number : ";
echo hexadecagonalNum($n);
// This code is contributed bu m_kit
?>
548
Chapter 98. Hexadecagonal number
Output :
Reference: https://en.wikipedia.org/wiki/Polygonal_number
Improved By : vt_m, jit_t
Source
https://www.geeksforgeeks.org/hexadecagonal-number/
549
Chapter 99
1) Draw a horizontal line to the right of each point and extend it to infinity
550
Chapter 99. How to check if a given point lies inside or outside a polygon?
1) Count the number of times the line intersects with polygon edges.
551
Chapter 99. How to check if a given point lies inside or outside a polygon?
552
Chapter 99. How to check if a given point lies inside or outside a polygon?
// p2, q2 and q1 are colinear and q1 lies on segment p2q2
if (o4 == 0 && onSegment(p2, q1, q2)) return true;
return false; // Doesn't fall in any of the above cases
}
// Returns true if the point p lies inside the polygon[] with n vertices
bool isInside(Point polygon[], int n, Point p)
{
// There must be at least 3 vertices in polygon[]
if (n < 3) return false;
// Create a point for line segment from p to infinite
Point extreme = {INF, p.y};
// Count intersections of the above line with sides of polygon
int count = 0, i = 0;
do
{
int next = (i+1)%n;
// Check if the line segment from 'p' to 'extreme' intersects
// with the line segment from 'polygon[i]' to 'polygon[next]'
if (doIntersect(polygon[i], polygon[next], p, extreme))
{
// If the point 'p' is colinear with line segment 'i-next',
// then check if it lies on segment. If it lies, return true,
// otherwise false
if (orientation(polygon[i], p, polygon[next]) == 0)
return onSegment(polygon[i], p, polygon[next]);
count++;
}
i = next;
} while (i != 0);
// Return true if count is odd, false otherwise
return count&1; // Same as (count%2 == 1)
}
// Driver program to test above functions
int main()
{
Point polygon1[] = {{0, 0}, {10, 0}, {10, 10}, {0, 10}};
int n = sizeof(polygon1)/sizeof(polygon1[0]);
Point p = {20, 20};
isInside(polygon1, n, p)? cout << "Yes \n": cout << "No \n";
553
Chapter 99. How to check if a given point lies inside or outside a polygon?
p = {5, 5};
isInside(polygon1, n, p)? cout << "Yes \n": cout << "No \n";
Point polygon2[] = {{0, 0}, {5, 5}, {5, 0}};
p = {3, 3};
n = sizeof(polygon2)/sizeof(polygon2[0]);
isInside(polygon2, n, p)? cout << "Yes \n": cout << "No \n";
p = {5, 1};
isInside(polygon2, n, p)? cout << "Yes \n": cout << "No \n";
p = {8, 1};
isInside(polygon2, n, p)? cout << "Yes \n": cout << "No \n";
Point polygon3[] = {{0, 0}, {10, 0}, {10, 10}, {0, 10}};
p = {-1,10};
n = sizeof(polygon3)/sizeof(polygon3[0]);
isInside(polygon3, n, p)? cout << "Yes \n": cout << "No \n";
return 0;
}
Output:
No
Yes
Yes
Yes
No
No
Time Complexity: O(n) where n is the number of vertices in the given polygon.
Source:
http://www.dcs.gla.ac.uk/~pat/52233/slides/Geometry1x1.pdf
Source
https://www.geeksforgeeks.org/how-to-check-if-a-given-point-lies-inside-a-polygon/
554
Chapter 100
The idea is to pick any point and calculate its distance from rest of the points. Let the
picked picked point be ‘p’. To form a square, distance of two points must be same from ‘p’,
let this distance be d. The distance from one point must be different from that d and must
be equal to √2 times d. Let this point with different distance be ‘q’.
The above condition is not good enough as the the point with different distance can be on
the other side. We also need to check that q is at same distance from 2 other points and
this distance is same as d.
Below is C++ implementation of above idea.
555
Chapter 100. How to check if given four points form a square
556
Chapter 100. How to check if given four points form a square
Output:
Yes
Extended Problem:
Check if four segments form a rectangle
This article is contributed by Anuj. Please write comments if you find anything incorrect,
or you want to share more information about the topic discussed above
Improved By : Sukanta_it
Source
https://www.geeksforgeeks.org/check-given-four-points-form-square/
557
Chapter 101
558
Chapter 101. How to check if two given line segments intersect?
Examples:
2. Special Case
– (p1, q1, p2), (p1, q1, q2), (p2, q2, p1), and (p2, q2, q1) are all collinear and
– the x-projections of (p1, q1) and (p2, q2) intersect
– the y-projections of (p1, q1) and (p2, q2) intersect
Examples:
559
Chapter 101. How to check if two given line segments intersect?
{
int x;
int y;
};
// Given three colinear points p, q, r, the function checks if
// point q lies on line segment 'pr'
bool onSegment(Point p, Point q, Point r)
{
if (q.x <= max(p.x, r.x) && q.x >= min(p.x, r.x) &&
q.y <= max(p.y, r.y) && q.y >= min(p.y, r.y))
return true;
return false;
}
// To find orientation of ordered triplet (p, q, r).
// The function returns following values
// 0 --> p, q and r are colinear
// 1 --> Clockwise
// 2 --> Counterclockwise
int orientation(Point p, Point q, Point r)
{
// See https://www.geeksforgeeks.org/orientation-3-ordered-points/
// for details of below formula.
int val = (q.y - p.y) * (r.x - q.x) -
(q.x - p.x) * (r.y - q.y);
if (val == 0) return 0; // colinear
return (val > 0)? 1: 2; // clock or counterclock wise
}
// The main function that returns true if line segment 'p1q1'
// and 'p2q2' intersect.
bool doIntersect(Point p1, Point q1, Point p2, Point q2)
{
// Find the four orientations needed for general and
// special cases
int o1 = orientation(p1, q1, p2);
int o2 = orientation(p1, q1, q2);
int o3 = orientation(p2, q2, p1);
int o4 = orientation(p2, q2, q1);
// General case
if (o1 != o2 && o3 != o4)
return true;
560
Chapter 101. How to check if two given line segments intersect?
Output:
No
Yes
No
Sources:
http://www.dcs.gla.ac.uk/~pat/52233/slides/Geometry1x1.pdf
Introduction to Algorithms 3rd Edition by Clifford Stein, Thomas H. Cormen, Charles E.
Leiserson, Ronald L. Rivest
561
Chapter 101. How to check if two given line segments intersect?
Source
https://www.geeksforgeeks.org/check-if-two-given-line-segments-intersect/
562
Chapter 102
Icosagonal number
Input : 3
Output :57
Input :8
Output :512
563
Chapter 102. Icosagonal number
C++
Java
564
Chapter 102. Icosagonal number
int n = 7;
System.out.print (n + "th Icosagonal number :");
System.out.println(icosagonal_poly(n));
}
}
// This code is contributed by aj_36
Python 3
C#
// C# program to find
// nth Icosagonal number
using System;
class GFG
{
// Function to calculate
// Icosagonal number
static int icosagonal_poly(int n)
{
// Formula for finding
// nth Icosagonal number
return (18 * n * n -
16 * n) / 2;
565
Chapter 102. Icosagonal number
}
// Driver code
static public void Main ()
{
int n = 7;
Console.Write(n + "th Icosagonal " +
"number :");
Console.WriteLine(icosagonal_poly(n));
}
}
// This code is contributed by ajit
PHP
<?php
// PHP program to find
// nth Icosagonal number
// Function to calculate
// Icosagonal number
function icosagonal_poly($n)
{
// Formula for finding
// nth Icosagonal number
return (18 * $n *
$n - 16 * $n) / 2;
}
// Driver Code
$n = 7;
echo $n , "th Icosagonal number :",
icosagonal_poly($n);
// This code is contributed by ajit
?>
Output :
Reference: https://en.wikipedia.org/wiki/Polygonal_number
Improved By : jit_t
566
Chapter 102. Icosagonal number
Source
https://www.geeksforgeeks.org/icosagonal-number/
567
Chapter 103
Icosahedral Number
Input : 5
Output :255
Input :10
Output :2260
568
Chapter 103. Icosahedral Number
int icosahedralnum(int n)
{
// Formula to calculate nth
// Icosahedral number &
// return it into main function.
return (n * (5 * n * n - 5 * n + 2)) / 2;
}
// Driver Code
int main()
{
int n = 7;
cout << icosahedralnum(n);
return 0;
}
Java
569
Chapter 103. Icosahedral Number
Python3
C#
570
Chapter 103. Icosahedral Number
{
int n = 7;
Console.WriteLine(icosahedralnum(n));
}
}
// This code is contributed by ajit
PHP
<?php
// Icosahedral number to
// find n-th term in PHP
// Function to find
// Icosahedral number
function icosahedralnum($n)
{
// Formula to calculate nth
// Icosahedral number &
// return it into main function.
return ($n * (5 * $n * $n -
5 * $n + 2)) / 2;
}
// Driver Code
$n = 7;
echo icosahedralnum($n);
// This code is contributed by m_kit
?>
Output
742
Improved By : jit_t
Source
https://www.geeksforgeeks.org/icosahedral-number/
571
Chapter 104
Icosidigonal number
Input : 2
Output :22
Input :6
Output :306
572
Chapter 104. Icosidigonal number
C++
Java
573
Chapter 104. Icosidigonal number
return (20 * n * n - 18 * n) / 2;
}
// Driver Code
public static void main (String[] args)
{
int n = 4;
System.out.print (n + "th Icosidigonal number :");
System.out.println (icosidigonal_num(n));
n = 8;
System.out.print (n + "th Icosidigonal number :");
System.out.println (icosidigonal_num(n));
}
}
// This code is contributed by ajit
Python 3
574
Chapter 104. Icosidigonal number
C#
PHP
<?php
// PHP program to find nth
// Icosidigonal number
// Function to calculate
// Icosidigonal number
function icosidigonal_num($n)
{
575
Chapter 104. Icosidigonal number
Output :
Reference: https://en.wikipedia.org/wiki/Polygonal_number
Improved By : jit_t
Source
https://www.geeksforgeeks.org/icosidigonal-number/
576
Chapter 105
Intersecting rectangle when bottom-left and top-right corners of two rectangles are given -
GeeksforGeeks
Given coordinates of 4 points, bottom-left and top-right corners of two rectangles. The task
is to find the coordinates of the intersecting rectangle formed by the given two rectangles.
577
Chapter 105. Intersecting rectangle when bottom-left and top-right corners of two
rectangles are given
Examples:
Input:
rec1: bottom-left(0, 0), top-right(10, 8),
rec2: bottom-left(2, 3), top-right(7, 9)
Output: (2, 3) (7, 8) (2, 8) (7, 3)
Input:
rec1: bottom-left(0, 0), top-right(3, 3),
rec2: bottom-left(1, 1), top-right(2, 2)
Output: (1, 1) (2, 2) (1, 2) (2, 1)
Approach :
As two given points are diagonals of a rectangle. so, x1 < x2, y1 < y2. similarly x3 < x4,
y3 < y4.
so, bottom-left and top-right points of intersection rectangle can be found by using formula.
x5 = max(x1, x3);
y5 = max(y1, y3);
x6 = min(x2, x4);
y6 = min(y2, y4);
In case of no intersection, x5 and y5 will always exceed x6 and y5 respectively. The other
two points of the rectangle can be found by using simple geometry.
Below is the implementation of the above approach:
C++
578
Chapter 105. Intersecting rectangle when bottom-left and top-right corners of two
rectangles are given
579
Chapter 105. Intersecting rectangle when bottom-left and top-right corners of two
rectangles are given
Java
580
Chapter 105. Intersecting rectangle when bottom-left and top-right corners of two
rectangles are given
Output:
581
Chapter 105. Intersecting rectangle when bottom-left and top-right corners of two
rectangles are given
Source
https://www.geeksforgeeks.org/intersecting-rectangle-when-bottom-left-and-top-right-corners-of-two-rectangles-are
582
Chapter 106
The algorithm was proposed by Klee in 1977. The time complexity of the algorithm is O
(N log N). It has been proven that this algorithm is the fastest (asymptotically) and this
problem can not be solved with a better complexity.
583
Chapter 106. Klee’s Algorithm (Length Of Union Of Segments of a line)
// Create a vector to store starting and ending
// points
vector <pair <int, bool> > points(n * 2);
for (int i = 0; i < n; i++)
{
points[i*2] = make_pair(seg[i].first, false);
points[i*2 + 1] = make_pair(seg[i].second, true);
}
// Sorting all points by point value
sort(points.begin(), points.end());
int result = 0; // Initialize result
// To keep track of counts of current open segments
// (Starting point is processed, but ending point
// is not)
int Counter = 0;
// Trvaerse through all points
for (unsigned i=0; i<n*2; i++)
{
// If there are open points, then we add the
// difference between previous and current point.
// This is interesting as we don't check whether
// current point is opening or closing,
if (Counter)
result += (points[i].first - points[i-1].first);
// If this is an ending point, reduce, count of
// open points.
(points[i].second)? Counter-- : Counter++;
}
return result;
}
// Driver program for the above code
int main()
{
vector< pair <int,int> > segments;
segments.push_back(make_pair(3, 15));
segments.push_back(make_pair(2, 5));
segments.push_back(make_pair(4, 8));
segments.push_back(make_pair(9, 12));
cout << "Length of Union of All segments = ";
cout << segmentUnionLength(segments) << endl;
return 0;
584
Chapter 106. Klee’s Algorithm (Length Of Union Of Segments of a line)
Output:
Description :
1) Put all the coordinates of all the segments in an auxiliary array points[].
2) Sort it on the value of the coordinates.
3) An additional condition for sorting – if there are equal coordinates, insert the one which
is the left coordinate of any segment instead of a right one.
4) Now go through the entire array, with the counter “count” of overlapping segments.
5) If count is greater than zero, then the result is added to the difference between the
points[i] – points[i-1].
6) If the current element belongs to the left end, we increase “count”, otherwise reduce it.
Illustration:
Counter = result = 0;
n = number of segments = 3;
Therefore :
points = {2, 5, 4, 8, 9, 12}
{f, t, f, t, f, t}
Now,
for i=0, result = 0;
Counter = 1;
585
Chapter 106. Klee’s Algorithm (Length Of Union Of Segments of a line)
Final answer = 9;
Source
https://www.geeksforgeeks.org/klees-algorithm-length-union-segments-line/
586
Chapter 107
587
Chapter 107. LS3/NS3 sphere generation algorithm and its implementation
I strongly suggest you that if you do not have any prerequisites in this field than go to
below link. This will help you to gain some prerequisites and concepts which are required
to understand the following implementation and algorithm.
Algorithm LS3 primarily focuses on generating the voxels of prima quadraginta . prima
quadraginta is formed when a discrete sphere is partitioned into 48 parts such that all 48
parts having some symmetrical relation and they all can be generated by using any one of
its parts. that one part is called as prima quadraginta (see figure 2). similarly, quadraginta
octant defined as same as prima qudraginta except that it is partitioned into 8 equal parts
instead of 48. quadaginta octant contains 6 prima quadraginta which are clearly shown in
the figure below. Q denotes to prima quadraginta (q-octant) and C denotes to quadraginta
octant(c-octant).a naive arc are those set of voxels which are having same x coordinate in
prima quadraginta (in above figure, the red voxels are making a naive arc).
By dint of 48 symmetric property, a whole discrete sphere can be developed from its prima
quadraginta. the limitation of using 48 symmetry is that some of the voxels of
q-octant will be repeated because they are sharing an edge or voxels with other
adjacent prima quadraginta. for example, In above figure, the voxels shown in
grey belongs to two or more q-octants.
Our algorithm will generate some repeated voxels therefore, we need to make some restric-
tions on input voxels.
In order to do this, I have included some functions in my implementation which are:
All these methods principally focuses on grey voxels (See above figure) expect
one putpixelall() which is going to produce all voxels except grey voxels by using
48 symmetry without any restrictions.
putpixeledge1 : This function will produce all voxels which has exactly one coordinate
zero
and if we proceed to find another voxel using symmetry and take an image with respect to
that zero coordinate
axis (this (0, 2, -1) voxel will have the same image if we take an image with respect to the
x-axis) then it comes
out to be the same voxel.
putpixeledge2 : These set of voxels having x and y coordinate are same (see prima quadrag-
inta figure 2).In order to store these voxels we have to look for a relation between q1 and q2
octants( see above table). you can achieve the general coordinate of any voxel in q2 from
q1 by swapping first (x, y) and then (y, z).
putpixelsingle : These pixels is very less in count.they are situated in the middle of
quadraginta octant (c octant) and shared with all the q-octants which are lying in the
same c-octant. to obtained these voxels we can see the above table and write all the voxels
corresponding to its c-octant.
putpixeldouble : These set of voxels having y and z coordinate are same (see prima
qudraginta figure 2).In order to store these voxels we need to find a relation between q1 and
q6 octants( see table). you can achieve the general coordinate of any voxel in q6 from q1 by
swapping first (y, z) and then (x, y).
putpixelmiddle : These set of voxels are located in those points where exactly two coordi-
nate
588
Chapter 107. LS3/NS3 sphere generation algorithm and its implementation
value is NULL which can help us to find to obtain the coordinates of these voxels( you can
write the coordinates
of these voxels manually).
We need an efficient storage of all the integer points (voxels) which will be formed by this
algorithm. In order to store these points, we will use hashmap and key value of hashmap
will be x coordinate of point and data value will be linked list of pair of y and z coordinate.
#include <iostream>
#include <cmath>
// this header file contains get<0> and get<1> function
#include <utility>
#include <list>
#include <map>
using namespace std;
// map to store the voxels
map<int, list<pair<int, int> > > mymap;
map<int, list<pair<int, int> > >::iterator itr;
// this function will store single voxel
void putpixelone(int m, int n, int p)
{
mymap[m].push_back(make_pair(n, p));
}
// function to store some particular type of voxel
void putpixelmiddle(int a, int b, int c, int x, int y, int z)
{
putpixelone(a + x, b + y, c + z);
putpixelone(a + x, b + y, -c + z);
putpixelone(a + x, c + y, b + z);
putpixelone(a + x, -c + y, b + z);
putpixelone(c + x, a + y, b + z);
putpixelone(-c + x, a + y, b + z);
}
// This program will generate 24 voxels
void putpixeldouble(int a, int b, int c, int x, int y, int z)
{
for (int j = 0; j < 3; j++) {
putpixelone(a + x, b + y, c + z);
swap(b, c);
swap(a, b);
}
for (int j = 0; j < 3; j++) {
putpixelone(-a + x, b + y, c + z);
589
Chapter 107. LS3/NS3 sphere generation algorithm and its implementation
swap(b, c);
swap(a, b);
}
for (int j = 0; j < 3; j++) {
putpixelone(a + x, -b + y, c + z);
swap(b, c);
swap(a, b);
}
for (int j = 0; j < 3; j++) {
putpixelone(-a + x, -b + y, c + z);
swap(b, c);
swap(a, b);
}
for (int j = 0; j < 3; j++) {
putpixelone(a + x, b + y, -c + z);
swap(b, c);
swap(a, b);
}
for (int j = 0; j < 3; j++) {
putpixelone(-a + x, b + y, -c + z);
swap(b, c);
swap(a, b);
}
for (int j = 0; j < 3; j++) {
putpixelone(a + x, -b + y, -c + z);
swap(b, c);
swap(a, b);
}
for (int j = 0; j < 3; j++) {
putpixelone(-a + x, -b + y, -c + z);
swap(b, c);
swap(a, b);
}
}
// Explained above
void putpixelsingle(int a, int b, int c, int x,
int y, int z)
{
putpixelone(a + x, b + y, c + z);
putpixelone(-a + x, b + y, c + z);
putpixelone(a + x, -b + y, c + z);
putpixelone(-a + x, -b + y, c + z);
putpixelone(a + x, b + y, -c + z);
putpixelone(-a + x, b + y, -c + z);
putpixelone(a + x, -b + y, -c + z);
putpixelone(-a + x, -b + y, -c + z);
}
590
Chapter 107. LS3/NS3 sphere generation algorithm and its implementation
591
Chapter 107. LS3/NS3 sphere generation algorithm and its implementation
592
Chapter 107. LS3/NS3 sphere generation algorithm and its implementation
putpixelone(a + x, -c + y, -b + z);
putpixelone(-c + x, a + y, -b + z);
putpixelone(-b + x, -c + y, a + z);
putpixelone(-a + x, b + y, -c + z);
putpixelone(b + x, -a + y, -c + z);
putpixelone(-c + x, b + y, -a + z);
putpixelone(-a + x, -c + y, b + z);
putpixelone(-c + x, -a + y, b + z);
putpixelone(b + x, -c + y, -a + z);
putpixelone(-a + x, b + y, c + z);
putpixelone(b + x, -a + y, c + z);
putpixelone(c + x, b + y, -a + z);
putpixelone(-a + x, c + y, b + z);
putpixelone(c + x, -a + y, b + z);
putpixelone(b + x, c + y, -a + z);
putpixelone(a + x, -b + y, c + z);
putpixelone(-b + x, a + y, c + z);
putpixelone(c + x, -b + y, a + z);
putpixelone(a + x, c + y, -b + z);
putpixelone(c + x, a + y, -b + z);
putpixelone(-b + x, c + y, a + z);
putpixelone(a + x, b + y, -c + z);
putpixelone(b + x, a + y, -c + z);
putpixelone(-c + x, b + y, a + z);
putpixelone(a + x, -c + y, b + z);
putpixelone(-c + x, a + y, b + z);
putpixelone(b + x, -c + y, a + z);
putpixelone(-a + x, -b + y, -c + z);
putpixelone(-b + x, -a + y, -c + z);
putpixelone(-c + x, -b + y, -a + z);
putpixelone(-a + x, -c + y, -b + z);
putpixelone(-c + x, -a + y, -b + z);
putpixelone(-b + x, -c + y, -a + z);
}
// detailed explanation of this algorithm is
// given in above link.
void drawsphere(int x, int y, int z, int r)
{
int i = 0, j = 0;
int k0 = r;
int k = k0;
int s0 = 0;
int s = s0;
int v0 = r - 1;
int v = v0;
int l0 = 2 * v0;
int l = l0;
593
Chapter 107. LS3/NS3 sphere generation algorithm and its implementation
// this while loop will form naive arcs
while (i <= k) {
// this while will form voxels in naive arcs
while (j <= k) {
if (s > v) {
k = k - 1;
v = v + l;
l = l - 2;
}
if ((j <= k) && ((s != v) || (j != k))) {
// this if, else and else if condition
// can easily build using figure 2, 3
if (i == 0 && j != 0)
// First naive arc pixels and each
// pixel is shared with two q-octants
putpixeledge1(i, j, k, x, y, z);
// voxels shared between q1 and q2
else if (i == j && j != k && i != 0)
putpixeledge2(i, j, k, x, y, z);
// center voxel of c-octants
else if (i == j && j == k)
putpixelsingle(i, j, k, x, y, z);
// voxels shared between q1 and q6
else if (j == k && i < k && i < j)
putpixeldouble(i, j, k, x, y, z);
// starting voxel of q-octant
else if (i == 0 && j == 0)
putpixelmiddle(i, j, k, x, y, z);
// voxels inside the q-octant
else
putpixelall(i, j, k, x, y, z);
}
s = s + 2 * j + 1;
j = j + 1;
}
s0 = s0 + 4 * i + 2;
i = i + 1;
while ((s0 > v0) && (i <= k0)) {
594
Chapter 107. LS3/NS3 sphere generation algorithm and its implementation
k0 = k0 - 1;
v0 = v0 + l0;
l0 = l0 - 2;
}
j = i;
k = k0;
v = v0;
l = l0;
s = s0;
}
}
// Print out all the voxels of discrete sphere
void showallpoints(map<int, list<pair<int, int> > >& mymap)
{
int count = 0;
for (itr = mymap.begin(); itr != mymap.end(); ++itr) {
list<pair<int, int> > l = itr->second;
list<pair<int, int> >::iterator it;
for (it = l.begin(); it != l.end(); ++it) {
cout << itr->first << ", " << get<0>(*it)
<< ", " << get<1>(*it) << endl;
count += 1;
}
}
cout << endl;
cout << count << endl;
}
// Driver program
int main()
{
int cx, cy, cz;
cin >> cx >> cy >> cz;
int r;
cin >> r;
drawsphere(cx, cy, cz, r);
showallpoints(mymap);
}
595
Chapter 107. LS3/NS3 sphere generation algorithm and its implementation
References :
http://www.sciencedirect.com/science/article/pii/S0304397515010178#tl0010
Source
https://www.geeksforgeeks.org/ls3ns3-sphere-generation-algorithm-implementation/
596
Chapter 108
Lexicographically Kth smallest way to reach given coordinate from origin - GeeksforGeeks
Given a coordinate (x, y) on a 2D plane. We have to reach (x, y) from the current position
which is at origin i.e (0, 0). In each step, we can either move vertically or horizontally on
the plane. While moving horizontally each step we write ‘H’ and while moving vertically
each step we write ‘V’. So, there can be possibly many strings containing ‘H’ and ‘V’ which
represents a path from (0, 0) to (x, y). The task is to find the lexicographically Kth smallest
string among all the possible strings.
Examples:
Input: x = 2, y = 2, k = 2
Output: HVVH
Explanation: There are 6 ways to reach (2, 2) from (0, 0). The possible
list of strings in lexicographically sorted order: [“HHVV”, “HVHV”, “HVVH”,
“VHHV”, “VHVH”, “VVHH”]. Hence, the lexicographically 2nd smallest string
is HVHV.
Input : x = 2, y = 2, k = 3
Output : VHHV
597
Chapter 108. Lexicographically Kth smallest way to reach given coordinate from origin
have already made a step in the vertical direction, so 1 is subtracted from y. Since ‘H’ is
lexicographically smaller than ‘V’, so among all stringsa starting strings will contains ‘H’ in
the beginning i.e inital movements will be Horizontal.
So, if K <= x + y – 1 Cx – 1 , we will take ‘H’ as first step else we will take ‘V’ as first step
and solve for number of goings to (x, y) from(1, 0) will be K = K – x + y – 1 Cx – 1 .
Below is the implementation of this approach:
C++
598
Chapter 108. Lexicographically Kth smallest way to reach given coordinate from origin
Java
599
Chapter 108. Lexicographically Kth smallest way to reach given coordinate from origin
600
Chapter 108. Lexicographically Kth smallest way to reach given coordinate from origin
System.out.print("V");
// recursive call to
// take next step.
Ksmallest(x, y, k);
}
// If on x-axis
else if (y == 0)
{
// decrement x.
x--;
// Move horizontal.
System.out.print("H");
// recursive call to
// take next step.
Ksmallest(x, y, k);
}
else
{
// If x + y C x is
// greater than K
if (factorial(x - 1, y) > k)
{
// Move Horizontal
System.out.print( "H");
// recursive call to
// take next step.
Ksmallest(x - 1, y, k);
}
else
{
// Move vertical
System.out.print("V");
// recursive call to
// take next step.
Ksmallest(x, y - 1, k -
factorial(x - 1, y));
}
}
}
// Driver Code
public static void main (String[] args)
601
Chapter 108. Lexicographically Kth smallest way to reach given coordinate from origin
{
int x = 2, y = 2, k = 2;
Ksmallest(x, y, k);
}
}
// This code is contributed
// by anuj_67.
Output
HVVH
Improved By : vt_m
Source
https://www.geeksforgeeks.org/lexicographically-kth-smallest-way-reach-given-coordinate-origin/
602
Chapter 109
Cohen-Sutherland algorithm divides a two-dimensional space into 9 regions and then ef-
ficiently determines the lines and portions of lines that are inside the given rectangular
area.
The algorithm can be outlines as follows:-
603
Chapter 109. Line Clipping | Set 1 (Cohen–Sutherland Algorithm)
1. Completely inside the given rectangle : Bitwise OR of region of two end points
of line is 0 (Both points are inside the rectangle)
2. Completely outside the given rectangle : Both endpoints share at least one
outside region which implies that the line does not cross the visible region. (bitwise
AND of endpoints != 0).
3. Partially inside the window : Both endpoints are in different regions. In this case,
the algorithm finds one of the two points that is outside the rectangular region. The
intersection of the line from outside point and rectangular window becomes new corner
point and the algorithm repeats
604
Chapter 109. Line Clipping | Set 1 (Cohen–Sutherland Algorithm)
Pseudo Code:
605
Chapter 109. Line Clipping | Set 1 (Cohen–Sutherland Algorithm)
606
Chapter 109. Line Clipping | Set 1 (Cohen–Sutherland Algorithm)
while (true)
{
if ((code1 == 0) && (code2 == 0))
{
// If both endpoints lie within rectangle
accept = true;
break;
}
else if (code1 & code2)
{
// If both endpoints are outside rectangle,
// in same region
break;
}
else
{
// Some segment of line lies within the
// rectangle
int code_out;
double x, y;
// At least one endpoint is outside the
// rectangle, pick it.
if (code1 != 0)
code_out = code1;
else
code_out = code2;
// Find intersection point;
// using formulas y = y1 + slope * (x - x1),
// x = x1 + (1 / slope) * (y - y1)
if (code_out & TOP)
{
// point is above the clip rectangle
x = x1 + (x2 - x1) * (y_max - y1) / (y2 - y1);
y = y_max;
}
else if (code_out & BOTTOM)
{
// point is below the rectangle
x = x1 + (x2 - x1) * (y_min - y1) / (y2 - y1);
y = y_min;
}
else if (code_out & RIGHT)
{
// point is to the right of rectangle
y = y1 + (y2 - y1) * (x_max - x1) / (x2 - x1);
607
Chapter 109. Line Clipping | Set 1 (Cohen–Sutherland Algorithm)
x = x_max;
}
else if (code_out & LEFT)
{
// point is to the left of rectangle
y = y1 + (y2 - y1) * (x_min - x1) / (x2 - x1);
x = x_min;
}
// Now intersection point x,y is found
// We replace point outside rectangle
// by intersection point
if (code_out == code1)
{
x1 = x;
y1 = y;
code1 = computeCode(x1, y1);
}
else
{
x2 = x;
y2 = y;
code2 = computeCode(x2, y2);
}
}
}
if (accept)
{
cout <<"Line accepted from " << x1 << ", "
<< y1 << " to "<< x2 << ", " << y2 << endl;
// Here the user can add code to display the rectangle
// along with the accepted (portion of) lines
}
else
cout << "Line rejected" << endl;
}
// Driver code
int main()
{
// First Line segment
// P11 = (5, 5), P12 = (7, 7)
cohenSutherlandClip(5, 5, 7, 7);
// Second Line segment
// P21 = (7, 9), P22 = (11, 4)
cohenSutherlandClip(7, 9, 11, 4);
608
Chapter 109. Line Clipping | Set 1 (Cohen–Sutherland Algorithm)
Python
609
Chapter 109. Line Clipping | Set 1 (Cohen–Sutherland Algorithm)
610
Chapter 109. Line Clipping | Set 1 (Cohen–Sutherland Algorithm)
Output:
611
Chapter 109. Line Clipping | Set 1 (Cohen–Sutherland Algorithm)
The Cohen–Sutherland algorithm can be used only on a rectangular clip window. For other
convex polygon clipping windows, Cyrus–Beck algorithm is used. We will be discussing
Cyrus–Beck Algorithm in next set.
Related Post :
Polygon Clipping | Sutherland–Hodgman Algorithm
Point Clipping Algorithm in Computer Graphics
Reference:
https://en.wikipedia.org/wiki/Cohen–Sutherland_algorithm
Source
https://www.geeksforgeeks.org/line-clipping-set-1-cohen-sutherland-algorithm/
612
Chapter 110
Examples :
Input : R = 1
Output : 4.25
(4*1^2 + 0.25) = 4.25
Input : R = 2
Output : 16.25
613
Chapter 110. Maximize a value for a semicircle of given radius
3.) Since QS = 2R
4*R^2 + PQ - PQ^2 = PS^2 + PQ
=> 4*R^2 + PQ - PQ^2 = F
C++
614
Chapter 110. Maximize a value for a semicircle of given radius
JAVA
Python3
615
Chapter 110. Maximize a value for a semicircle of given radius
print(maximumValueOfF(R))
# This code is contributed by Sam007.
C#
PHP
<?php
// PHP program to find the
// maximum value of F
// Function to find the
// maximum value of F
function maximumValueOfF ($R)
{
// using the formula derived
// for getting the maximum
616
Chapter 110. Maximize a value for a semicircle of given radius
// value of F
return 4 * $R * $R + 0.25;
}
// Drivers code
$R = 3;
echo maximumValueOfF($R);
// This code is contributed
// by anuj_67.
?>
Output :
36.25
Source
https://www.geeksforgeeks.org/maximize-a-value-for-a-semicircle-of-given-radius/
617
Chapter 111
Input : s = 4
Output : 2
Only possible dimensions are some combination of 1, 1, 2.
Input : s = 8
Output : 18
All possible edge dimensions:
[1, 1, 6], volume = 6
[1, 2, 5], volume = 10
[1, 3, 4], volume = 12
[2, 2, 4], volume = 16
[2, 3, 3], volume = 18
C++
618
Chapter 111. Maximize volume of cuboid with given sum of sides
#include <bits/stdc++.h>
using namespace std;
// Return the maximum volume.
int maxvolume(int s)
{
int maxvalue = 0;
// for length
for (int i = 1; i <= s - 2; i++) {
// for breadth
for (int j = 1; j <= s - 1; j++) {
// for height
int k = s - i - j;
// calculating maximum volume.
maxvalue = max(maxvalue, i * j * k);
}
}
return maxvalue;
}
// Driven Program
int main()
{
int s = 8;
cout << maxvolume(s) << endl;
return 0;
}
Java
619
Chapter 111. Maximize volume of cuboid with given sum of sides
{
// for breadth
for (int j = 1; j <= s - 1; j++)
{
// for height
int k = s - i - j;
// calculating maximum volume.
maxvalue = Math.max(maxvalue, i * j * k);
}
}
return maxvalue;
}
// Driver function
public static void main (String[] args)
{
int s = 8;
System.out.println(maxvolume(s));
}
}
// This code is contributed by Anant Agarwal.
Python3
620
Chapter 111. Maximize volume of cuboid with given sum of sides
return maxvalue
# Driven Program
s = 8
print(maxvolume(s))
# This code is contributed by "Sharad_Bhardwaj".
C#
621
Chapter 111. Maximize volume of cuboid with given sum of sides
}
}
// This code is contributed by vt_m.
PHP
<?php
// PHP code to Maximize volume of
// cuboid with given sum of sides
// Return the maximum volume.
function maxvolume( $s)
{
$maxvalue = 0;
// for length
for ( $i = 1; $i <= $s - 2; $i++)
{
// for breadth
for ( $j = 1; $j <= $s - 1; $j++)
{
// for height
$k = $s - $i - $j;
// calculating maximum volume.
$maxvalue = max($maxvalue,
$i * $j * $k);
}
}
return $maxvalue;
}
// Driver Code
$s = 8;
echo(maxvolume($s));
// This code is contributed by vt_m.
?>
Output :
18
622
Chapter 111. Maximize volume of cuboid with given sum of sides
C++
#include <bits/stdc++.h>
using namespace std;
// Return the maximum volume.
int maxvolume(int s)
{
// finding length
int length = s / 3;
s -= length;
// finding breadth
int breadth = s / 2;
// finding height
int height = s - breadth;
return length * breadth * height;
}
// Driven Program
int main()
{
int s = 8;
cout << maxvolume(s) << endl;
return 0;
}
Java
623
Chapter 111. Maximize volume of cuboid with given sum of sides
class GFG
{
// Return the maximum volume.
static int maxvolume(int s)
{
// finding length
int length = s / 3;
s -= length;
// finding breadth
int breadth = s / 2;
// finding height
int height = s - breadth;
return length * breadth * height;
}
// Driven Program
public static void main (String[] args)
{
int s = 8;
System.out.println ( maxvolume(s));
}
}
// This code is contributed by vt_m.
Python3
624
Chapter 111. Maximize volume of cuboid with given sum of sides
height = s - breadth
return int(length * breadth * height)
# Driven Program
s = 8
print( maxvolume(s) )
# This code is contributed by "Sharad_Bhardwaj".
C#
PHP
625
Chapter 111. Maximize volume of cuboid with given sum of sides
<?php
// Return the maximum volume.
function maxvolume($s)
{
// finding length
$length = (int)($s / 3);
$s -= $length;
// finding breadth
$breadth = (int)($s / 2);
// finding height
$height = $s - $breadth;
return $length * $breadth * $height;
}
// Driven Code
$s = 8;
echo(maxvolume($s));
// This code is contributed by Ajit.
?>
Output :
18
626
Chapter 111. Maximize volume of cuboid with given sum of sides
Source
https://www.geeksforgeeks.org/maximize-volume-cuboid-given-sum-sides/
627
Chapter 112
Input : 1 2 1 2
Output : 2.00
It is optimal to construct a rectangle for maximum area .
628
Chapter 112. Maximum area of quadrilateral
C
c γ
D
δ
θ
d b
e f
α
A
a β
B
According to Bretschneider’s formula, the area of a general quadilateral is given by
629
Chapter 112. Maximum area of quadrilateral
{
// Calculating the semi-perimeter
// of the given quadilateral
double semiperimeter = (a + b + c + d) / 2;
// Applying Brahmagupta's formula to
// get maximum area of quadrilateral
return sqrt((semiperimeter - a) *
(semiperimeter - b) *
(semiperimeter - c) *
(semiperimeter - d));
}
// Driver code
int main()
{
double a = 1, b = 2, c= 1, d = 2;
printf("%.2f\n",maxArea(a, b, c, d));
return 0;
}
Java
630
Chapter 112. Maximum area of quadrilateral
System.out.println(maxArea(a, b, c, d));
}
}
// This code is contributed by sunnysingh
Python3
C#
631
Chapter 112. Maximum area of quadrilateral
PHP
<?php
// PHP program to find maximum are of a
// quadrilateral
function maxArea( $a, $b, $c, $d)
{
// Calculating the semi-perimeter
// of the given quadilateral
$semiperimeter = ($a + $b + $c + $d) / 2;
// Applying Brahmagupta's formula to
// get maximum area of quadrilateral
return sqrt(($semiperimeter - $a) *
($semiperimeter - $b) *
($semiperimeter - $c) *
($semiperimeter - $d));
}
// Driver code
$a = 1; $b = 2; $c= 1; $d = 2;
echo(maxArea($a, $b, $c, $d));
// This code is contributed by vt_m.
632
Chapter 112. Maximum area of quadrilateral
?>
Output:
2.00
Improved By : vt_m
Source
https://www.geeksforgeeks.org/maximum-area-quadrilateral/
633
Chapter 113
Input : Line 1 : x1 = 1, y1 = 1, x2 = 2, y2 = 2
Line 2 : x2 = 2, y1 = 2, x2 = 4, y2 = 10
Output : 2
There are two lines. These two lines are not
parallel, so both of them will pass through
a single point.
Input : Line 1 : x1 = 1, y1 = 5, x2 = 1, y2 = 10
Line 2 : x2 = 5, y1 = 1, x2 = 10, y2 = 1
Output : 2
634
Chapter 113. Maximum distinct lines passing through a single point
We can calculate slope of a line as , add them to a set and count the number
of distinct values of slope in set. But we have to handle vertical lines separately.
So, if then, slope = INT_MAX.
Otherwise, slope = .
Bellow is the implementation of the approach.
Output:
635
Chapter 113. Maximum distinct lines passing through a single point
Time Complexity:
Source
https://www.geeksforgeeks.org/maximum-distinct-lines-passing-through-a-single-point/
636
Chapter 114
Input : N = 7
Output : 3
Maximum height will be 3, putting 1, 2 and
then 3 coins. It is not possible to use 1
coin left.
Input : N = 12
Output : 4
Maximum height will be 4, putting 1, 2, 3 and
4 coins, it is not possible to make height as 5,
because that will require 15 coins.
This problem can be solved by finding a relation between height of the triangle and number
of coins. Let maximum height is H, then total sum of coin should be less than N,
637
Chapter 114. Maximum height when coins are arranged in a triangle
CPP
638
Chapter 114. Maximum height when coins are arranged in a triangle
return 0;
}
Java
639
Chapter 114. Maximum height when coins are arranged in a triangle
int N = 12;
System.out.print(findMaximumHeight(N));
}
}
// This code is contributed by Anant Agarwal.
Python3
640
Chapter 114. Maximum height when coins are arranged in a triangle
C#
641
Chapter 114. Maximum height when coins are arranged in a triangle
PHP
<?php
// PHP program to find maximum height
// of arranged coin triangle
/* Returns the square root of n. Note
that the function */
function squareRoot( $n)
{
/* We are using n itself as initial
approximation This can definitely
be improved */
$x = $n;
$y = 1;
/* e decides the accuracy level*/
$e = 0.000001;
while ($x - $y > $e)
{
$x = ($x + $y) / 2;
$y = $n/$x;
}
return $x;
}
// Method to find maximum height of
// arrangement of coins
function findMaximumHeight( $N)
{
// calculating portion inside
// the square root
$n = 1 + 8 * $N;
$maxH = (-1 + squareRoot($n)) / 2;
return floor($maxH);
}
// Driver code to test above method
$N = 12;
echo findMaximumHeight($N) ;
// This code is contributed by anuj_67.
?>
Output:
642
Chapter 114. Maximum height when coins are arranged in a triangle
Improved By : vt_m
Source
https://www.geeksforgeeks.org/maximum-height-coins-arranged-triangle/
643
Chapter 115
Input : 4 4
Output : 0 4
1 3
2 2
3 1
4 0
Explanation : Distance between any two points
mentioned in output is not integer.
Firstly, we want to create a set, that means our set cannot contain any other point with
same x’s or y’s which are used before. Well, the reason behind it is that such points which
either have same x-coordinate or y-coordinate would cancel that coordinate, resulting an
integral distance between them.
Example, consider points (1, 4) and (1, 5), the x-coordinate would cancel and thus, we will
get and integral distance.
Secondly, we can observe that, we have only x+1 distinct i-coordinates and y+1 distinct
j-coordinates. Thus, the size of the set cannot exceed min(x, y)+1.
Third observation is that we know that the diagonal elements are |i-j|* distance
apart, thus, we take evaluate along the diagonal element of i-coordinate and calculate the
j-coordinate by formula min(i, j)-i.
644
Chapter 115. Maximum integral co-ordinates with non-integer distances
Output:
0 4
1 3
2 2
3 1
4 0
Source
https://www.geeksforgeeks.org/maximum-integral-co-ordinates-non-integer-distances/
645
Chapter 116
Maximum number of 2x2 squares that can be fit inside a right isosceles triangle - Geeks-
forGeeks
What is the maximum number of squares of size 2×2 units that can be fit in a right angled
isosceles triangle of a given base (in units).
A side of the square must be parallel to the base of the triangle.
Examples:
Input : 8
Output : 6
Please refer below diagram for explanation.
Input : 7
Output : 3
Since the triangle is isosceles, the given base would also be equal to the height. Now in the
diagonal part, we would always need an extra length of 2 units in both height and base of
the triangle to accommodate a triangle. (The CF and AM segment of the triangle in the
image. The part that does not contribute to any square). In the remaining length of base,
we can construct length / 2 squares. Since each square is of 2 units, same would be the case
of height, there is no need to calculate that again.
So, for each level of given length we can construct “(length-2)/2” squares. This gives us
a base of “(length-2)” above it. Continuing this process to get the no of squares for all
available “length-2” height, we can calculate the squares.
646
Chapter 116. Maximum number of 2×2 squares that can be fit inside a right isosceles
triangle
C++
Java
647
Chapter 116. Maximum number of 2×2 squares that can be fit inside a right isosceles
triangle
Python3
C#
648
Chapter 116. Maximum number of 2×2 squares that can be fit inside a right isosceles
triangle
PHP
<?php
// PHP program to count number of 2 x 2
// squares in a right isosceles triangle
function numberOfSquares( $base)
{
// removing the extra
// part we would
// always need
$base = ($base - 2);
// Since each square
// has base of
// length of 2
$base = $base / 2;
649
Chapter 116. Maximum number of 2×2 squares that can be fit inside a right isosceles
triangle
return $base * ($base + 1)/2;
}
// Driver code
$base = 8;
echo numberOfSquares($base);
// This code is contributed by anuj_67.
?>
Output:
Improved By : vt_m
Source
https://www.geeksforgeeks.org/maximum-number-2x2-squares-can-fit-inside-right-isosceles-triangle/
650
Chapter 117
Input : n = 1
Output : 2
Explanation :
Input : n = 2
Output : 4
Explanation :
Input : n = 3
Output : 6
Explanation :
651
Chapter 117. Maximum number of pieces in N cuts
C++
Java
// Java program to find maximum
// no of pieces by given number
// of cuts
import java.util.*;
class GFG
{
// Function for finding maximum
652
Chapter 117. Maximum number of pieces in N cuts
Improved By : Kirti_Mangal
Source
https://www.geeksforgeeks.org/maximum-number-of-pieces-in-n-cuts/
653
Chapter 118
Maximum number of squares that can fit in a right angle isosceles triangle - GeeksforGeeks
You are given an isosceles (a triangle with at-least two equal sides) right angle triangle with
base b, we need to find the maximum number of squares of side m, which can be fitted into
given triangle.
Examples:
Input : b = 6, m = 2
Output : 3
Input : b = 4, m = 1
Output : 6
Let’s consider a right angle triangle XYZ, where YZ is the base of triangle. Suppose length
of the base is b. If we consider the position of first square with the vertex Y, we will have
(b / m-1) squares in the base, and we will be left with another isosceles right angle triangle
having base length (b – m).
Illustration :
654
Chapter 118. Maximum number of squares that can fit in a right angle isosceles triangle
Let f(b, m) = Number of squares which can be fitted in triangle having base length b.
then f(b, m) = (b / m – 1) + f(b – m, m)
We can calculate f(b) using above recursion, and with use of memoization. Later we can
answer each query in O(1) time. We can do it for even and odd numbers separately with
the base case if (b < 2 * m) f(b, m) = 0.
The given recursion can be solved as :
f(b, m) = b / m – 1 + f(b – m, m) = b / m – 1 + (b – m) / m – 1 + f(b – 2m, m)
f(b, m) = b / m – 1 + b / m – 2 + f(b – 3m, m) +…+ f(b – (b / m)m, m)
f(b) = b / m – 1 + b / m – 2 + b / m – 3 +…..+ 1 + 0
With conditions, if (b < 2 * m) f(b, m) = 0
f(b) = sum of first (b / m – 1) natural numbers
= (b / m – 1) * (b / m) / 2
This formula can be used to reduce the time complexity upto O(1).
C++
655
Chapter 118. Maximum number of squares that can fit in a right angle isosceles triangle
Java
Python3
656
Chapter 118. Maximum number of squares that can fit in a right angle isosceles triangle
C#
PHP
657
Chapter 118. Maximum number of squares that can fit in a right angle isosceles triangle
<?php
// PHP program for finding
// maximum squares that can
// fit in right angle isosceles
// triangle
// function for finding
// max squares
function maxSquare($b, $m)
{
// return in O(1) with
// derived formula
return ($b / $m - 1) *
($b / $m) / 2;
}
// Driver Code
$b = 10; $m = 2;
echo maxSquare($b,$m);
// This code is contribute by vt_m
?>
Output:
10
Improved By : vt_m
Source
https://www.geeksforgeeks.org/maximum-number-of-squares-that-can-be-fit-in-a-right-angle-isosceles-triangle/
658
Chapter 119
Input : n = 2
Output : 2
Input : n = 3
Output : 6
As we can see in above diagram, for each pair of circles, there can be maximum two inter-
sectuib points. Therefore if we have n circles then there can be n C2 pairs of circles in which
each pair will have two intersections. So by this we can conclude that by looking at all
possible pairs of circles the mathematical formula can be made for the maximum number
of intersection by n circles is given by 2 * n C2 .
2 * n C2 = 2 * n * (n – 1)/2 = n * (n-1)
C++
659
Chapter 119. Maximum points of intersection n circles
int intersection(int n)
{
return n * (n - 1);
}
int main()
{
cout << intersection(3) << endl;
return 0;
}
// This code is contributed by
// Manish Kumar Rai.
Java
Python3
660
Chapter 119. Maximum points of intersection n circles
C#
php
<?php
// php program to find maximum umber of
// intersections of n circles
// Returns maximum number of intersections
function intersection($n)
{
return $n * ($n - 1);
}
// Drive code
echo intersection(3);
// This code is contributed by Sam007
?>
Output:
Improved By : Sam007
661
Chapter 119. Maximum points of intersection n circles
Source
https://www.geeksforgeeks.org/maximum-points-intersection-n-circles/
662
Chapter 120
Input: c1 = 1, c2 = 2, c3 = 3, L = 1, K = 0
Output: 0
Since, no center can be moved, there is no intersection among three segments
{(0.5, 1.5), (1.5, 2.5), (2.5, 3.5)}.
Input: c1 = 1, c2 = 2, c3 = 3, L = 1, K = 1
Output: 1
Center’s 1 and 3 can be shifted 1 unit ahead and forward respectively to overlap
with center 2
Approach: Initially sort the centers, since the middle segment will never move as left and
right segment can always reach near to its center to increase the intersection length. There
will be three cases which are to be dealt with:
663
Chapter 120. Maximum possible intersection by moving centers of line segments
• Case 1: When the distance between centers of the right and left is more than or
equal to 2*K+L in such scenario intersection will always be zero. No overlapping is
possible since even after shifting both centers with K distance still, they will be away
at a distance of L or more.
• Case 2: When the distance between centers of the right and left is more than or
equal to 2*K in such scenario there exists an intersection which is equal to (2 * k –
(center[2] – center[0] – length)) which can be calculated using simple maths.
• Case 3: When the distance between centers of the right and left is less than 2*K in
such case both centers can coincide with the middle center. Hence, the intersection is
L.
C++
#include <bits/stdc++.h>
using namespace std;
// Function to print the maximum intersection
int max_intersection(int* center, int length, int k)
{
sort(center, center + 3);
// Case 1
if (center[2] - center[0] >= 2 * k + length) {
return 0;
}
// Case 2
else if (center[2] - center[0] >= 2 * k) {
return (2 * k - (center[2] - center[0] - length));
}
// Case 3
else
return length;
}
// Driver Code
int main()
{
int center[3] = { 1, 2, 3 };
int L = 1;
int K = 1;
cout << max_intersection(center, L, K);
}
Java
664
Chapter 120. Maximum possible intersection by moving centers of line segments
// Java implementation
// of above approach
import java.util.*;
class GFG
{
// Function to print the
// maximum intersection
static int max_intersection(int center[],
int length, int k)
{
Arrays.sort(center);
// Case 1
if (center[2] - center[0] >= 2 * k + length)
{
return 0;
}
// Case 2
else if (center[2] - center[0] >= 2 * k)
{
return (2 * k - (center[2] -
center[0] - length));
}
// Case 3
else
return length;
}
// Driver Code
public static void main(String args[])
{
int center[] = { 1, 2, 3 };
int L = 1;
int K = 1;
System.out.println( max_intersection(center, L, K));
}
}
// This code is contributed
// by Arnab Kundu
C#
// C# implementation
665
Chapter 120. Maximum possible intersection by moving centers of line segments
// of above approach
using System;
class GFG
{
// Function to print the
// maximum intersection
static int max_intersection(int []center,
int length, int k)
{
Array.Sort(center);
// Case 1
if (center[2] - center[0] >= 2 * k + length)
{
return 0;
}
// Case 2
else if (center[2] -
center[0] >= 2 * k)
{
return (2 * k - (center[2] -
center[0] - length));
}
// Case 3
else
return length;
}
// Driver Code
public static void Main()
{
int []center = { 1, 2, 3 };
int L = 1;
int K = 1;
Console.WriteLine(max_intersection(center, L, K));
}
}
// This code is contributed
// by Subhadeep Gupta
PHP
= 2 * $k + $length)
{
666
Chapter 120. Maximum possible intersection by moving centers of line segments
return 0;
}
// Case 2
else if ($center[2] –
$center[0] >= 2 * $k)
{
return (2 * $k – ($center[2] –
$center[0] – $length));
}
// Case 3
else
return $length;
}
// Driver Code
$center = array(1, 2, 3);
$L = 1;
$K = 1;
echo max_intersection($center, $L, $K);
// This code is contributed
// by mits
?>
Output:
Source
https://www.geeksforgeeks.org/maximum-possible-intersection-by-moving-centers-of-line-segments/
667
Chapter 121
Two triangulations of the same convex pentagon. The triangulation on the left has a cost
of 8 + 2√2 + 2√5 (approximately 15.30), the one on the right has a cost of 4 + 2√2 + 4√5
(approximately 15.77).
This problem has recursive substructure. The idea is to divide the polygon into three parts:
a single triangle, the sub-polygon to the left, and the sub-polygon to the right. We try all
possible divisions like this and find the one that minimizes the cost of the triangle plus the
cost of the triangulation of the two sub-polygons.
668
Chapter 121. Minimum Cost Polygon Triangulation
minCost(i, j) = 0
Else
minCost(i, j) = Min { minCost(i, k) + minCost(k, j) + cost(i, k, j) }
Here k varies from 'i+1' to 'j-1'
669
Chapter 121. Minimum Cost Polygon Triangulation
Output:
15.3006
The above problem is similar to Matrix Chain Multiplication. The following is recursion
tree for mTC(points[], 0, 4).
670
Chapter 121. Minimum Cost Polygon Triangulation
It can be easily seen in the above recursion tree that the problem has many overlapping sub-
problems. Since the problem has both properties: Optimal Substructure and Overlapping
Subproblems, it can be efficiently solved using dynamic programming.
Following is C++ implementation of dynamic programming solution.
671
Chapter 121. Minimum Cost Polygon Triangulation
Output:
15.3006
672
Chapter 121. Minimum Cost Polygon Triangulation
Sources:
http://www.cs.utexas.edu/users/djimenez/utsa/cs3343/lecture12.html
http://www.cs.utoronto.ca/~heap/Courses/270F02/A4/chains/node2.html
Source
https://www.geeksforgeeks.org/minimum-cost-polygon-triangulation/
673
Chapter 122
Input : n = 4
Output : 8
Minimum possible perimeter with 4 blocks
is 8. See below explanation.
Input : n = 11
Output : 14
The square grid of above examples would be as
Let us take an example to see a pattern. Let us say that we have 4 blocks, following are
different possibilities
+--+--+--+--+
| | | | | Perimeter = 10
+--+--+--+--+
+--+--+--+
| | | | Perimeter = 10
+--+--+--+
| |
+--+
674
Chapter 122. Minimum Perimeter of n blocks
+--+--+--+
| | | | Perimeter = 10
+--+--+--+
| |
+--+
+--+--+
| | | Perimeter = 8
+--+--+
| | |
+--+--+
If we do some examples using pen and paper, we can notice that the perimeter becomes
minimum when the shape formed is closest to a square. The reason for this is, we want
maximum sides of blocks to face inside the shape so that perimeter of the shape becomes
minimum.
If the Number of blocks is a perfect square then the perimeter would simply be 4*sqrt(n).
But, if the Number of blocks is not a perfect square root then we calculate number of rows
and columns closest to square root. After arranging the blocks in a rectangular we still have
blocks left then we will simply add 2 to the perimeter because only 2 extra side would be
left.
The implementation of the above idea is given below.
C++
675
Chapter 122. Minimum Perimeter of n blocks
= 2 * (l + row);
// if there are blocks left
if (n % l != 0)
perimeter += 2;
return perimeter;
}
}
// Driver code
int main()
{
int n = 10;
cout << minPerimeter(n);
return 0;
}
Java
676
Chapter 122. Minimum Perimeter of n blocks
}
// Driver code
public static void main(String[] args)
{
int n = 10;
System.out.println(minPerimeter(n));
}
}
// This code is contributed by Arnav Kr. Mandal
Python3
C#
677
Chapter 122. Minimum Perimeter of n blocks
PHP
<?php
// PHP program to find minimum
// perimeter using n blocks.
function minPerimeter($n)
{
678
Chapter 122. Minimum Perimeter of n blocks
$l = floor(sqrt($n));
$sq = $l * $l;
// if n is a perfect square
if ($sq == $n)
return $l * 4;
else
{
// Number of rows
$row = floor($n / $l);
// perimeter of the
// rectangular grid
$perimeter = 2 * ($l + $row);
// if there are blocks left
if ($n % $l != 0)
$perimeter += 2;
return $perimeter;
}
}
// Driver code
$n = 10;
echo minPerimeter($n);
// This code is contributed
// by nitin mittal.
?>
Output :
14
References :
http://mathforum.org/library/drmath/view/61595.html
intermath.coe.uga.edu/tweb/gcsu-geo-spr06/aheath/aheath_rectperimeter.doc
Improved By : nitin mittal, Prasad_Kshirsagar
Source
https://www.geeksforgeeks.org/minimum-perimeter-n-blocks/
679
Chapter 123
One thing to note in question before we proceed is that the number of sides must be at least
4 (note n > 3 condition)..
Here, we have to find the minimum area possible for a regular polygon, so to calculate
minimum possible area, we need calculate required value of n . As the side length is not
given, so we first calculate circumradius of the triangle formed by the points. It is given
by the formula
R = abc / 4A
where a, b, c are the sides of the triangle formed and A is the area of the traingle. Here,
the area of triangle can be calculated by Heron’s Formula .
After calculating circumradius of the triangle, we calculate the area of the polygon by the
formula
A = nX ( sin(360/n) xr2 /2 )
680
Chapter 123. Minimum area of a Polygon with three points given
681
Chapter 123. Minimum area of a Polygon with three points given
Output:
1.00
Source
https://www.geeksforgeeks.org/minimum-area-polygon-three-points-given/
682
Chapter 124
Input : Lines = [x = 0, y = 0, x + y – 2 = 0]
Start point = [1, 1],
Dest point = [-2, -1]
Output : 2
We need to jump 2 times (B4 -> B3 then B3 -> B5
or B4 -> B6 then B6 -> B5) to reach destination
point from starting point shown in below diagram.
Each block i is given an id Bi in the diagram.
We can solve this problem using a property of lines and points which is stated as, If we put
two points in line equation then they will have same sign i.e. positive-positive or negative-
negative of evaluated value if both points lies on the same side of line, in case of different
sign i.e. positive-negative they will lie on different side of line.
Now we can use above property to solve this problem, For each line, we will check if start
and destination point lie on the same side or not. If they lie to the different side of a line
then that line must be jumped to come closer. As in above diagram start point and the
destination point are on the same side of x + y – 2 = 0 line, so that line need not to be
jumped, rest two lines need to be jumped because both points lies on opposite side.
Finally, we will check the sign of evaluation of points with respect to each line and we will
683
Chapter 124. Minimum block jumps to reach destination
increase our jump count whenever we found opposite signs. Total time complexity of this
problem will be linear.
684
Chapter 124. Minimum block jumps to reach destination
Output:
Source
https://www.geeksforgeeks.org/minimum-block-jumps-reach-destination/
685
Chapter 125
686
Chapter 125. Minimum distance to travel to cover all intervals
We can solve this problem by concentrating only on endpoints. Since the requirement is to
cover all intervals by reaching a point, all intervals must a share a point for answer to exist.
Even the interval with leftmost end point must overlap with the interval right most start
point.
First, we find right most start point and left most end point from all intervals. Then we
can compare our position with these points to get the result which is explained below :
1. If this right most start point is to the right of left most end point then it is not possible
to cover all intervals simultaneously. (as in example 2)
2. If our position is in mid between to right most start and left most end then there is no
need to travel and all intervals will be covered by current position only (as in example
3)
3. If our position is left to both points then we need to travel up to the rightmost start
point and if our position is right to both points then we need to travel up to leftmost
end point.
Refer above diagram to understand these cases. As in the first example, right most start is
4 and left most end is 6, so we need to reach 4 from current position 3 to cover all intervals.
Please see below code for better understanding.
687
Chapter 125. Minimum distance to travel to cover all intervals
rightMostStart = intervals[i].start;
if (leftMostEnd > intervals[i].end)
leftMostEnd = intervals[i].end;
}
int res;
/* if rightmost start > leftmost end then all
intervals are not aligned and it is not
possible to cover all of them */
if (rightMostStart > leftMostEnd)
res = -1;
// if x is in between rightmoststart and
// leftmostend then no need to travel any distance
else if (rightMostStart <= x && x <= leftMostEnd)
res = 0;
// choose minimum according to current position x
else
res = (x < rightMostStart) ? (rightMostStart - x) :
(x - leftMostEnd);
return res;
}
// Driver code to test above methods
int main()
{
int x = 3;
Interval intervals[] = {{0, 7}, {2, 14}, {4, 6}};
int N = sizeof(intervals) / sizeof(intervals[0]);
int res = minDistanceToCoverIntervals(intervals, N, x);
if (res == -1)
cout << "Not Possible to cover all intervals\n";
else
cout << res << endl;
}
Output:
688
Chapter 125. Minimum distance to travel to cover all intervals
Source
https://www.geeksforgeeks.org/minimum-distance-travel-cover-intervals/
689
Chapter 126
Examples :
Input : a = 2, b = 2
690
Chapter 126. Minimum height of a triangle with given base and area
Explanation:
Input : a = 8, b = 4
Output : Minimum height of triangle is 4
Minimum height of Triangle with base “b” and area “a” can be evaluated by having the
knowledge of the relationship between the three.
C++
#include <bits/stdc++.h>
using namespace std;
// function to calculate minimum height of
// triangle
int minHeight(int base, int area){
return ceil((float)(2*area)/base);
}
int main() {
int base = 4, area = 8;
cout << "Minimum height is "
<< minHeight(base, area) << endl;
return 0;
}
Java
691
Chapter 126. Minimum height of a triangle with given base and area
Python
C#
692
Chapter 126. Minimum height of a triangle with given base and area
{
int b_ase = 4, area = 8;
Console.WriteLine("Minimum height is "
+ minHeight(b_ase, area));
}
}
// This code is contributed by vt_m.
PHP
<?php
// function to calculate minimum
// height of triangle
function minHeight($base, $area)
{
return ceil((2 * $area) / $base);
}
// Driver Code
$base = 4;$area = 8;
echo "Minimum height is ",
minHeight($base, $area);
// This code is contributed by anuj_67.
?>
Output :
Minimum height is 4
Improved By : vt_m
Source
https://www.geeksforgeeks.org/minimum-height-triangle-given-base-area/
693
Chapter 127
694
Chapter 127. Minimum length of the shortest path of a triangle
In the first example, the minimum length of the shortest path is equal to the maximum sum
of the points, which is 1+3 or 2+2. So the path which will cover all the points is (1, 4) and
(4, 1) on the coordinate axis.
Below is the step by step algorithm to solve this problem:
695
Chapter 127. Minimum length of the shortest path of a triangle
// traversing through each points on the plane
int i = 0;
while (n--) {
// if sum of a points is greater than the
// previous one, the maximum gets replaced
if (x[i] + y[i] > answer)
answer = x[i] + y[i];
i++;
}
// print the length
cout << "Length -> " << answer << endl;
cout << "Path -> "
<< "( 1, " << answer << " )"
<< "and ( " << answer << ", 1 )";
}
// Driver code
int main()
{
// initialize the number of points
int n = 4;
// points on the plane
int x[n] = { 1, 4, 2, 1 };
int y[n] = { 4, 1, 1, 2 };
shortestLength(n, x, y);
return 0;
}
Output:
Length -> 5
Path -> ( 1, 5 )and ( 5, 1 )
Source
https://www.geeksforgeeks.org/minimum-length-of-the-shortest-path-of-a-triangle/
696
Chapter 128
If given points are (-1, 3), (4, 3), (2, 1), (-1, -2),
(3, -3) and (xO, yO) point is (1, 0) i.e. every line
must go through this point.
Then we have to draw at least two lines to cover all
these points going through (xO, yO) as shown in below
diagram.
We can solve this problem by considering the slope of all points with (xO, yO). If two distinct
points have the same slope with (xO, yO) then they can be covered with same line only so
we can track slope of each point and whenever we get a new slope we will increase our line
count by one.
In below code slope is stored as a pair of integer to get rid of the precision problem and a
set is used to keep track of occurred slopes.
Please see below code for better understanding.
697
Chapter 128. Minimum lines to cover all points
698
Chapter 128. Minimum lines to cover all points
}
}
return minLines;
}
// Driver code to test above methods
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;
}
Output:
Source
https://www.geeksforgeeks.org/minimum-lines-cover-points/
699
Chapter 129
Minimum number of points to be removed to get remaining points on one side of axis -
GeeksforGeeks
We are given n points in a Cartesian plane. Our task is to find the minimum number of
points that should be removed in order to get the remaining points on one side of any axis.
Examples :
Input : 4
1 1
2 2
-1 -1
-2 2
Output : 1
Explanation :
If we remove (-1, -1) then all the remaining
points are above x-axis. Thus the answer is 1.
Input : 3
1 10
2 3
4 11
Output : 0
Explanation :
All points are already above X-axis. Hence the
answer is 0.
700
Chapter 129. Minimum number of points to be removed to get remaining points on one
side of axis
Approach :
This problem is a simple example of constructive brute force algorithm on Geometry. The
solution can be approached simply by finding the number of points on all sides of the X-axis
and Y-axis. The minimum of this will be the answer.
701
Chapter 129. Minimum number of points to be removed to get remaining points on one
side of axis
Output :
Source
https://www.geeksforgeeks.org/minimum-number-points-removed-get-remaining-points-one-side-axis/
702
Chapter 130
Minimum number of square tiles required to fill the rectangular floor - GeeksforGeeks
Given a rectanglular floor of (M X N) meters is to be paved with square tiles of (s X s).
The task is to find the minimum number of tiles required to pave the rectangular floor.
Constraints:
1. It’s allowed to cover the surface larger than the floor, but the floor has to be covered.
2. It’s not allowed to break the tiles.
3. The sides of tiles should be parallel to the sides of the floor.
Examples:
Input: 2 1 2
Output: 1
length of floor = 2
breadth of floor = 1
length of side of tile = 2
No of tiles required for paving is 2.
Input: 222 332 5
Output: 3015
Approach:
It is given that edges of each tile must be parallel to edges of the tiles allows us to analyze
X and Y axes separately, that is, how many segments of length ‘s’ are needed to cover a
segment of length’ and ‘N’ — and take product of these two quantities.
703
Chapter 130. Minimum number of square tiles required to fill the rectangular floor
ceil(M/s) * ceil(N/s)
, where ceil(x) is the least integer which is above or equal to x. Using integers only, it is
usually written as
((M + s - 1) / s)*((N + s - 1) / s)
C++
704
Chapter 130. Minimum number of square tiles required to fill the rectangular floor
Java
// Java implementation
// of above approach
import java.util.*;
import java.lang.*;
import java.io.*;
class GFG
{
// Function to find the
// number of tiles
static int solve(int M, int N, int s)
{
// if breadth is divisible
// by side of square
if (N % s == 0)
{
// tiles required is N/s
N = N / s;
}
else
{
// one more tile required
N = (N / s) + 1;
}
// if length is divisible
// by side of square
if (M % s == 0)
{
// tiles required is M/s
M = M / s;
}
else
705
Chapter 130. Minimum number of square tiles required to fill the rectangular floor
{
// one more tile required
M = (M / s) + 1;
}
return M * N;
}
// Driver Code
public static void main(String args[])
{
// input length and breadth of
// rectangle and side of square
int N = 12, M = 13, s = 4;
System.out.println(solve(M, N, s));
}
}
// This code is contributed
// by ChitraNayal
Python 3
# Python 3 implementation of
# above approach
# Function to find the number
# of tiles
def solve(M, N, s) :
# if breadth is divisible
# by side of square
if (N % s == 0) :
# tiles required is N/s
N = N // s
else :
# one more tile required
N = (N // s) + 1
# if length is divisible by
# side of square
if (M % s == 0) :
706
Chapter 130. Minimum number of square tiles required to fill the rectangular floor
C#
707
Chapter 130. Minimum number of square tiles required to fill the rectangular floor
PHP
Output:
12
C++
708
Chapter 130. Minimum number of square tiles required to fill the rectangular floor
// Function to find the number of tiles
int solve(double M, double N, double s)
{
// no of tiles
int ans = ((int)(ceil(M / s)) * (int)(ceil(N / s)));
return ans;
}
// Driver Code
int main()
{
// input length and breadth of
// rectangle and side of square
double N = 12, M = 13, s = 4;
cout << solve(M, N, s);
return 0;
}
Java
709
Chapter 130. Minimum number of square tiles required to fill the rectangular floor
// This Code is contributed by mits
Output:
12
Source
https://www.geeksforgeeks.org/minimum-number-of-square-tiles-required-to-fill-the-rectangular-floor/
710
Chapter 131
Input : r = 2
x1 = 0, y1 = 0
x2 = 0, y2 = 4
Output :1
Input : r = 1
x1 = 1, y1 = 1,
x2 = 4, y2 = 4
Output : 3
Let’s consider a straight line between the two centers. Clearly to move the center with
maximum distance we need to rotate it around the the line and with 180 degrees. So the
maximum distance we can move the center each time is 2 * r. Let’s continue moving the
center with 2 * r distance each time until the two circles intersects. Now obviously we can
make the center moves into its final position by rotating it around one of the intersection
points of the two circles until it reaches the final destination.
Every time we make the circle moves 2 * r times except the last move it’ll be < 2 * r. Let
the initial distance between the two points be d. Solution to the problem will be ceil(d/2*r).
C++
711
Chapter 131. Minimum revolutions to move center of a circle to a target
Java
712
Chapter 131. Minimum revolutions to move center of a circle to a target
System.out.print((int)minRevolutions(r,
x1, y1, x2, y2));
}
}
// This code is contributed by Anant Agarwal.
Python3
C#
713
Chapter 131. Minimum revolutions to move center of a circle to a target
PHP
<?php
// PHP program to find minimum
// number of revolutions to reach
// a target center
// Minimum revolutions to move
// center from (x1, y1) to (x2, y2)
function minRevolutions($r, $x1, $y1,
$x2, $y2)
{
$d = sqrt(($x1 - $x2) * ($x1 - $x2) +
($y1 - $y2) * ($y1 - $y2));
return ceil($d / (2 * $r));
}
// Driver code
$r = 2; $x1 = 0; $y1 = 0; $x2 = 0; $y2 = 4;
echo minRevolutions($r, $x1, $y1, $x2, $y2);
// This code is contributed by nitin mittal.
?>
714
Chapter 131. Minimum revolutions to move center of a circle to a target
Output :
Source
https://www.geeksforgeeks.org/minimum-revolutions-move-center-circle-target/
715
Chapter 132
Input : 1 2 3
Output :1
We have a 3x3 square and we need
to make a rectangles of size 1x2.
So we need only square to cover the
rectangle.
Input : 11 23 14
Output :2
The only way to actually fill the rectangle optimally is to arrange each square such that it is
parallel to the sides of the rectangle.So we just need to find the number of squares to fully
cover the length and breadth of the rectangle.
The length of the rectangle is l, and if the side length of the square is a divides l, then there
must be l/a squares to cover the full length of l. If l isn’t divisible by a, we need to add 1
to l/a, to round it down.For this we can use the ceil function, as ceil(x) returns the least
integer which is above or equal to x.
We can do the same with the rectangle width, and take the number of squares across the
width to be ceil(b/a).
So, total number of squares=ceil(m/a) * ceil(n/a).
716
Chapter 132. Minimum squares to cover a rectangle
Output:
Source
https://www.geeksforgeeks.org/minimum-squares-to-cover-a-rectangle/
717
Chapter 133
718
Chapter 133. Mirror of a point through a 3 D plane
x = a*k + x1
y = b*k + y1
z = c*k + z1
719
Chapter 133. Mirror of a point through a 3 D plane
x2 = a * k + x1
y2 = b * k + y1
z2 = c * k + z1
Since, Point N(x2, y2, z2) is midpoint of point P(x1, y1, z1) and point Q(x3, y3, z3),
coordinates of Point Q are:-
=> x3 = 2 * x2 - x1
=> y3 = 2 * y2 - y1
=> z3 = 2 * z2 - z1
// C program to find
// Mirror of a point
// through a 3 D plane
#include<stdio.h>
// Function to mirror image
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;
printf("x3 = %.1f ", x3);
printf("y3 = %.1f ", y3);
printf("z3 = %.1f ", z3);
}
// Driver Code
int main()
{
float a = 1;
float b = -2;
float c = 0;
float d = 0;
float x1 = -1;
720
Chapter 133. Mirror of a point through a 3 D plane
float y1 = 3;
float z1 = 4;
// function call
mirror_point(a, b, c, d,
x1, y1, z1);
}
// This code is contributed
// by Amber_Saxena.
Java
721
Chapter 133. Mirror of a point through a 3 D plane
int x1 = -1;
int y1 = 3;
int z1 = 4;
// function call
mirror_point(a, b, c, d,
x1, y1, z1) ;
}
}
// This code is contributed
// by inder_verma
Python
PHP
<?php
// PHP program to find Mirror of
// a point through a 3 D plane
722
Chapter 133. Mirror of a point through a 3 D plane
// Function to mirror image
function mirror_point($a, $b, $c, $d,
$x1, $y1, $z1)
{
$k = (-$a * $x1 - $b *
$y1 - $c * $z1 - $d) /
($a * $a + $b *
$b + $c * $c);
$x2 = $a * $k + $x1;
$y2 = $b * $k + $y1;
$z2 = $c * $k + $z1;
$x3 = 2 * $x2 - $x1;
$y3 = 2 * $y2 - $y1;
$z3 = 2 * $z2 - $z1;
echo sprintf("x3 = %.1f ", $x3);
echo sprintf("y3 = %.1f ", $y3);
echo sprintf("z3 = %.1f ", $z3);
}
// Driver Code
$a = 1;
$b = -2;
$c = 0;
$d = 0;
$x1 = -1;
$y1 = 3;
$z1 = 4;
// function call
mirror_point($a, $b, $c, $d,
$x1, $y1, $z1);
// This code is contributed
// by Amber_Saxena.
?>
Output:
Source
https://www.geeksforgeeks.org/mirror-of-a-point-through-a-3-d-plane/
723
Chapter 134
The neighbours of any point on the discrete circle are those points which are
having one less or one more x coordinate from its original x coordinate.
We use bresenham’s circle generation algorithm to extract out integer points required to
draw a circle on computer screen of pixels.
724
Chapter 134. Neighbors of a point on a circle using Bresenham’s algorithm
Circle have the property of being highly symmetrical which is needed when it comes to
drawing them on the computer screen of pixels. Bresenham’s circle algorithm calculates the
locations of the pixels in the first 45 degrees and remaining pixels on the periphery of a
circle which is centered at origin are computed by using 8-way symmetry property of the
circle.
725
Chapter 134. Neighbors of a point on a circle using Bresenham’s algorithm
our limits are from (0, r) to (r/ , r/ ) where x = y. as we know that, In this
particular octant, the decrease in the y coordinate is less than increase in the x coordinate
or you can say that the movement along x axis is more than the movement along y axis so,
the x coordinate always increases in first octant. now, we want to know whether the y will
change with x or not. In order to know the variation of y with x, bresenham’s introduced a
variable named as decision parameter which will update their value as the loop runs.
Now, we need to understand that how we will choose the next pixel, In the figure, f(N) and
f(S) are errors involved in calculating the distances from origin to pixel N and S respectively
and whichever is comes out to be less we’ll choose that pixel. decision parameter is defined
as d = f(N)+f(S), if d <= 0 then N will be the next pixel otherwise S will be the next pixel.
we will keep doing this procedure until x<y condition holds and by taking all symmetric
points we will end up with all the integer points required to show a circle on computer screen
of pixels.
This article is not predominantly focused on bresenham’s algorithm therefore, I’ll skip the
derivation of decision parameter but if you want to understand of derivation of decision
parameter then go to the reference links.
Note: neighbors of a point can be of any number and y-coordinate of the neighbors should
have same sign as of its input pixel and for those pixels which have y coordinate zero we
will print out all the neighbors irrespective of its signs.
A discrete geometric object consists of a finite set of integer points. This set is usually very
sparse. Therefore, an array representation is not at all space efficient to store. we will use
hash map having data value is a linked list of y-coordinate and key value as x- coordinate.
we can easily access them using the key value and its also a space efficient.
Below is C++ stl program for determining Neighbors of a given point.
726
Chapter 134. Neighbors of a point on a circle using Bresenham’s algorithm
727
Chapter 134. Neighbors of a point on a circle using Bresenham’s algorithm
728
Chapter 134. Neighbors of a point on a circle using Bresenham’s algorithm
it->first == given_pointx - 1) {
list<int> temp1 = it->second;
list<int>::iterator itr1;
for (itr1 = temp1.begin(); itr1 != temp1.end(); ++itr1) {
// Checking for same-sign.
if (given_pointy >= 0 && *itr1 >= 0)
cout << "(" << it->first << ", " << *itr1 << ")\n";
else if (given_pointy <= 0 && *itr1 <= 0)
cout << "(" << it->first << ", " << *itr1 << ")\n";
else
continue;
}
}
}
}
// Driver code
int main()
{
int center_x = 0, center_y = 0;
float r = 3.0;
circle(center_x, center_y, r);
showallpoints(mymap);
int nx = 3, ny = 0;
neighbours(mymap, nx, ny);
cout << endl;
return 0;
}
Output:
(-3, 0), (-3, -1), (-3, 1), (-2, -2), (-2, 2), (-1, -3), (-1, 3), (0, 3)
(0, -3), (1, 3), (1, -3), (2, 2), (2, -2), (3, 0), (3, 1), (3, -1)
Neighbours of given point are : (2, 2), (2, -2)
References :
https://www.slideshare.net/tahersb/bresenham-circle
Source
https://www.geeksforgeeks.org/neighbors-point-circle-using-bresenhams-algorithm/
729
Chapter 135
Examples :
Input : n = 2
Output : 1
Input : n = 4
Output : 2
Input : n = 6
730
Chapter 135. Non-crossing lines to connect points in a circle
Output : 5
Input : n = 3
Output : Invalid
n must be even.
We need to draw n/2 lines to connect n points. When we draw a line, we divide the points
in two sets that need to connected. Each set needs to be connected within itself. Below is
recurrence relation for the same.
Let m = n/2
731
Chapter 135. Non-crossing lines to connect points in a circle
Java
732
Chapter 135. Non-crossing lines to connect points in a circle
// A dynamic programming
// based function to find
// nth Catalan number
static int catalanDP(int n)
{
// Table to store
// results of subproblems
int []catalan = new int [n + 1];
// Initialize first
// two values in table
catalan[0] = catalan[1] = 1;
// Fill entries in catalan[]
// using recursive formula
for (int i = 2; i <= n; i++)
{
catalan[i] = 0;
for (int j = 0; j < i; j++)
catalan[i] += catalan[j] *
catalan[i - j - 1];
}
// Return last entry
return catalan[n];
}
// Returns count of ways to
// connect n points on a circle
// such that no two connecting
// lines cross each other and
// every point is connected
// with one other point.
static int countWays(int n)
{
// Throw error if n is odd
if (n < 1)
{
System.out.println("Invalid");
return 0;
}
// Else return n/2'th
// Catalan number
return catalanDP(n / 2);
}
733
Chapter 135. Non-crossing lines to connect points in a circle
// Driver Code
public static void main (String[] args)
{
System.out.println(countWays(6) + " ");
}
}
// This code is contributed
// by akt_mit
C#
734
Chapter 135. Non-crossing lines to connect points in a circle
return catalan[n];
}
// Returns count of ways to
// connect n points on a circle
// such that no two connecting
// lines cross each other and
// every point is connected
// with one other point.
static int countWays(int n)
{
// Throw error if n is odd
if (n < 1)
{
Console.WriteLine("Invalid");
return 0;
}
// Else return n/2'th
// Catalan number
return catalanDP(n / 2);
}
// Driver Code
static public void Main ()
{
Console.WriteLine(countWays(6) + " ");
}
}
// This code is contributed
// by M_kit
PHP
<?php
// PHP program to count number of
// ways to connect n (where n is
// even) points on a circle such
// that no two connecting lines
// cross each other and every
// point is connected with one
// other point.
// A dynamic programming based
// function to find nth Catalan number
function catalanDP($n)
{
735
Chapter 135. Non-crossing lines to connect points in a circle
Output :
736
Chapter 135. Non-crossing lines to connect points in a circle
Source
https://www.geeksforgeeks.org/non-crossing-lines-connect-points-circle/
737
Chapter 136
Simple Approach
Start from any of the given points, reach the other end point by using loops. For every point
inside the loop, check if it lies on the line that joins given two points. If yes, then increment
the count by 1. Time Complexity for this approach will be O(min(x2-x1, y2-y1)).
Optimal Approach
738
Chapter 136. Number of Integral Points between Two Points
739
Chapter 136. Number of Integral Points between Two Points
Output:
Reference :
https://www.geeksforgeeks.org/count-integral-points-inside-a-triangle/
Please write comments if you find anything incorrect, or you want to share more information
about the topic discussed above
Improved By : nikhil52
Source
https://www.geeksforgeeks.org/number-integral-points-two-points/
740
Chapter 137
We can apply Euler Characteristics to find out number of Hexagons and Pentagons on a
741
Chapter 137. Number of Pentagons and Hexagons on a Football
standard Football.
According to Euler Characteristics: For every surface S there exists an integer
such that whenever a graph G with V vertices and E edges is embedded in S so that there
are F faces(regions divided by the graph), we have:
= 2.
Hence, the equation becomes V – E + F = 2.
Now, let number of pentagons P and number of hexagons H.
Number of vertices will be:
6 vertices for each of the hexagons, i.e. 6*H.
5 vertices for each of the pentagons, i.e. 5*P.
But we have counted each vertex thrice, once for each adjacent polygon, follow the picture
742
Chapter 137. Number of Pentagons and Hexagons on a Football
after solving this equation we will get P = 12. So, there are 12 Pentagons.
Now number of Hexagons:
We can see that each pentagon is surrounded by 5 Hexagons. So there should 5*P hexagons,
but we have counted each hexagon thrice for each of its 3 adjacent pentagons. Hence,
number of hexagons = 5*P/3 = 5*12/3 = 20.
Hence, there are 20 Hexagons and 12 Pentagons in a standard football.
743
Chapter 137. Number of Pentagons and Hexagons on a Football
Source
https://www.geeksforgeeks.org/number-pentagons-hexagons-football/
744
Chapter 138
Number of Triangles that can be formed given a set of lines in Euclidean Plane - Geeks-
forGeeks
Given a set L = {l1 , l2 , ………, ln } of ‘n’ distinct lines on the Euclidean Plane. The ith line
is given by an equation in the form ai x + bi y = ci . Find the number of triangles that can
be formed using the lines in the set L. Note that no two pairs of lines intersect at the same
point.
Note: This problem doesn’t mention that the lines can’t be parallel which makes the problem
difficult to solve.
Examples:
745
Chapter 138. Number of Triangles that can be formed given a set of lines in Euclidean
Plane
Time Complexity: There are n C3 triplets of lines. For each triplet, we have to do 3
comparisons to check that any 2 lines are not parallel which means the check can be done
in O(1) time. This makes the naive algorithm O(n3 ).
This can also be achieved in O(n log n). The logic behind the efficient algorithm is described
below.
We divide the set L in various subsets. The formation of subsets is based on slopes i.e. all
the lines in a particular subset have the same slope i.e. they are parallel to each other.
Let us consider three sets (say A, B and C). For a particular set (say A) the lines belonging
to this are all parallel to each other. If we have A, B and C, we can pick one line from each
set to get a triangle because none of these lines will be parallel. By making the subsets we
have ensured that no two lines which are parallel are being picked together.
746
Chapter 138. Number of Triangles that can be formed given a set of lines in Euclidean
Plane
747
Chapter 138. Number of Triangles that can be formed given a set of lines in Euclidean
Plane
count[k++] = this_count;
this_count = 1;
}
}
count[k++] = this_count;
// calculating sum1 (Sum of all slopes)
// sum1 = m1 + m2 + ...
int sum1 = 0;
for (int i=0; i<k; i++)
sum1 += count[i];
// calculating sum2. sum2 = m1*m2 + m2*m3 + ...
int sum2 = 0;
int temp[n]; // Needed for sum3
for (int i=0; i<k; i++)
{
temp[i] = count[i]*(sum1-count[i]);
sum2 += temp[i];
}
sum2 /= 2;
// calculating sum3 which gives the final answer
// m1 * m2 * m3 + m2 * m3 * m4 + ...
int sum3 = 0;
for (int i=0; i<k; i++)
sum3 += count[i]*(sum2-temp[i]);
sum3 /= 3;
return sum3;
}
// Driver code
int main()
{
// lines are stored as arrays of a, b
// and c for 'ax+by=c'
int a[] = {1, 2, 3, 4};
int b[] = {2, 4, 5, 5};
int c[] = {5, 7, 8, 6};
// n is the number of lines
int n = sizeof(a)/sizeof(a[0]);
cout << "The number of triangles that"
" can be formed are: "
<< numberOfTringles(a, b, c, n);
748
Chapter 138. Number of Triangles that can be formed given a set of lines in Euclidean
Plane
return 0;
}
Output:
Time Complexity: All the loops in the code are O(n). The time complexity in this
implementation is thus driven by the sort function used to sort the slope array. This makes
the algorithm O(nlogn).
Source
https://www.geeksforgeeks.org/number-triangles-can-formed-given-set-lines-euclidean-plane/
749
Chapter 139
The result is one if all points are on x axis or y axis. The result is 2 if points can form
L shape. L shape is formed if any of the three points can be used as a joining point.
Otherwise answer is 3.
C++
750
Chapter 139. Number of horizontal or vertical line segments to connect 3 points
// Function to check if the third point forms a
// rectangle with other two points at corners
bool isBetween(int a, int b, int c)
{
return min(a, b) <= c && c <= max(a, b);
}
// Returns true if point k can be used as a joining
// point to connect using two line segments
bool canJoin(int x[], int y[], int i, int j, int k)
{
// Check for the valid polyline with two segments
return (x[k] == x[i] || x[k] == x[j]) &&
isBetween(y[i], y[j], y[k]) ||
(y[k] == y[i] || y[k] == y[j]) &&
isBetween(x[i], x[j], x[k]);
}
int countLineSegments(int x[], int y[])
{
// Check whether the X-coordinates or
// Y-cocordinates are same.
if ((x[0] == x[1] && x[1] == x[2]) ||
(y[0] == y[1] && y[1] == y[2]))
return 1;
// Iterate over all pairs to check for two
// line segments
else if (canJoin(x, y, 0, 1, 2) ||
canJoin(x, y, 0, 2, 1) ||
canJoin(x, y, 1, 2, 0))
return 2;
// Otherwise answer is three.
else
return 3;
}
// Driver code
int main()
{
int x[3], y[3];
x[0] = -1; y[0] = -1;
x[1] = -1; y[1] = 3;
x[2] = 4; y[2] = 3;
cout << countLineSegments(x, y);
return 0;
751
Chapter 139. Number of horizontal or vertical line segments to connect 3 points
Java
752
Chapter 139. Number of horizontal or vertical line segments to connect 3 points
// Otherwise answer is three.
else
return 3;
}
// Driver code
public static void main (String[] args) {
int x[]=new int[3], y[]=new int[3];
x[0] = -1; y[0] = -1;
x[1] = -1; y[1] = 3;
x[2] = 4; y[2] = 3;
System.out.println(countLineSegments(x, y));
}
}
// This code is contributed by vt_m
Python3
753
Chapter 139. Number of horizontal or vertical line segments to connect 3 points
C#
754
Chapter 139. Number of horizontal or vertical line segments to connect 3 points
755
Chapter 139. Number of horizontal or vertical line segments to connect 3 points
y[2] = 3;
Console.WriteLine(countLineSegments(x, y));
}
}
// This code is contributed by vt_m.
PHP
<?php
// PHP program to find number
// of horizontal (or vertical
// line segments needed to
// connect three points.
// Function to check if the
// third point forms a
// rectangle with other
// two points at corners
function isBetween( $a, $b, $c)
{
return min($a, $b) <= $c and
$c <= max($a, $b);
}
// Returns true if point k
// can be used as a joining
// point to connect using
// two line segments
function canJoin($x, $y, $i, $j, $k)
{
// Check for the valid
// polyline with two segments
return ($x[$k] == $x[$i] or
$x[$k] == $x[$j]) and
isBetween($y[$i], $y[$j], $y[$k]) or
($y[$k] == $y[$i] or
$y[$k] == $y[$j]) and
isBetween($x[$i], $x[$j], $x[$k]);
}
function countLineSegments( $x, $y)
{
// Check whether the X-coordinates
// or Y-cocordinates are same.
if (($x[0] == $x[1] and $x[1] == $x[2]) or
756
Chapter 139. Number of horizontal or vertical line segments to connect 3 points
Output :
Improved By : vt_m
Source
https://www.geeksforgeeks.org/find-no-segments-polyline/
757
Chapter 140
Number of jump required of given length to reach a point of form (d, 0) from origin in 2D
plane - GeeksforGeeks
Given three positive integers a, b and d. You are currently at origin (0, 0) on infinite
2D coordinate plane. You are allowed to jump on any point in the 2D plane at euclidean
distance either equal to a or b from your current position. The task is to find the minimum
number of jump required to reach (d, 0) from (0, 0).
Examples:
Input : a = 2, b = 3, d = 1
Output : 2
First jump of length a = 2, (0, 0) -> (1/2, √15/2)
Second jump of length a = 2, (1/2, √15/2) -> (1, 0)
Thus, only two jump are required to reach
(1, 0) from (0, 0).
Input : a = 3, b = 4, d = 11
Output : 3
(0, 0) -> (4, 0) using length b = 4
(4, 0) -> (8, 0) using length b = 4
(8, 0) -> (11, 0) using length a = 3
First, observe we don’t need to find the intermediate points, we only want the minimum
number of jumps required.
758
Chapter 140. Number of jump required of given length to reach a point of form (d, 0) from
origin in 2D plane
So, from (0, 0) we will move in direction of (d, 0) i.e vertically with the jump of length equal
to max(a, b) until the Euclidean distance between the current position coordinate and (d,
0) either became less than max(a, b) or equal to 0. This will increase the minimum number
of jumps required by 1 at each jump. So this value can be found by floor(d/max(a, b)).
Now, for the rest of the distance, if (d, 0) is a Euclidean distance away, we will make one
jump of length a and reach the (d, 0). So, the minimum number of jumps required will be
increased by 1 in this case.
Now, let’s solve the case if rest of the distance is not equal to a. Let the rest of distance
left be x. Also, observe x will be greater than 0 and less than max(a, b), therefore, 0 < x
< 2*max(a, b). We can reach to (d, 0) in 2 steps.
How ?
Lets try to build a triangle ABC such that A is our current position, B is target position
i.e (d, 0) and C will be the point such that AC = BC = max(a, b). And this is possible to
triangle because sum of two side AC + BC is greater than third side AB. So, one jump is
from A to C and another jump from C to B.
Below is the implementation of this approach:
C++
#include <bits/stdc++.h>
using namespace std;
// Return the minimum jump of length either a or b
// required to reach (d, 0) from (0, 0).
int minJumps(int a, int b, int d)
{
// Assigning maximum of a and b to b
// and assigning minimum of a and b to a.
int temp = a;
a = min(a, b);
b = max(temp, b);
// if d is greater than or equal to b.
if (d >= b)
return (d + b - 1) / b;
// if d is 0
if (d == 0)
return 0;
// if d is equal to a.
if (d == a)
return 1;
// else make triangle, and only 2
// steps required.
759
Chapter 140. Number of jump required of given length to reach a point of form (d, 0) from
origin in 2D plane
return 2;
}
int main()
{
int a = 3, b = 4, d = 11;
cout << minJumps(a, b, d) << endl;
return 0;
}
Java
760
Chapter 140. Number of jump required of given length to reach a point of form (d, 0) from
origin in 2D plane
{
int a = 3, b = 4, d = 11;
System.out.println(minJumps(a, b, d));
}
}
// This code is contributed by vt_m
Python3
C#
761
Chapter 140. Number of jump required of given length to reach a point of form (d, 0) from
origin in 2D plane
class GFG {
// Return the minimum jump of length either a or b
// required to reach (d, 0) from (0, 0).
static int minJumps(int a, int b, int d)
{
// Assigning maximum of a and b to b
// and assigning minimum of a and b to a.
int temp = a;
a = Math.Min(a, b);
b = Math.Max(temp, b);
// if d is greater than or equal to b.
if (d >= b)
return (d + b - 1) / b;
// if d is 0
if (d == 0)
return 0;
// if d is equal to a.
if (d == a)
return 1;
// else make triangle, and only 2
// steps required.
return 2;
}
// Driver code
public static void Main()
{
int a = 3, b = 4, d = 11;
Console.WriteLine(minJumps(a, b, d));
}
}
// This code is contributed by vt_m
PHP
<?php
// PHP code to find the minimum
// number of jump required to
// reach (d, 0) from (0, 0).
// Return the minimum jump
762
Chapter 140. Number of jump required of given length to reach a point of form (d, 0) from
origin in 2D plane
// of length either a or b
// required to reach (d, 0)
// from (0, 0).
function minJumps( $a, $b, $d)
{
// Assigning maximum of
// a and b to b and
// assigning minimum of
// a and b to a.
$temp = $a;
$a = min($a, $b);
$b = max($temp, $b);
// if d is greater than
// or equal to b.
if ($d >= $b)
return ($d + $b - 1) / $b;
// if d is 0
if ($d == 0)
return 0;
// if d is equal to a.
if ($d == $a)
return 1;
// else make triangle,
// and only 2
// steps required.
return 2;
}
// Driver Code
$a = 3;
$b = 4;
$d = 11;
echo floor(minJumps($a, $b, $d));
// This code is contributed by anuj_67.
?>
Output
Improved By : vt_m
763
Chapter 140. Number of jump required of given length to reach a point of form (d, 0) from
origin in 2D plane
Source
https://www.geeksforgeeks.org/number-jump-required-given-length-reach-point-form-d-0-origin-2d-plane/
764
Chapter 141
Input : m = 1, c = 1, arr[] = [ 1, 2, 3, 4, 2 ]
Output : 5 ordered points
Explanation : The equation of the line with given slope and intercept is : y
= x + 1. The Number of pairs (i, j), for which (arri , arrj ) satisfies the above
equation of the line are : (1, 2), (1, 5), (2, 3), (3, 4), (5, 3).
Input : m = 2, c = 1, arr[] = [ 1, 2, 3, 4, 2, 5 ]
Output : 3 ordered points
Source
https://www.geeksforgeeks.org/number-ordered-points-pair-satisfying-line-equation/
C++
765
Chapter 141. Number of ordered points pair satisfying line equation
766
Chapter 141. Number of ordered points pair satisfying line equation
Java
767
Chapter 141. Number of ordered points pair satisfying line equation
768
Chapter 141. Number of ordered points pair satisfying line equation
}
// This code is contributed by
// Manish Shaw (manishshaw1)
Python3
769
Chapter 141. Number of ordered points pair satisfying line equation
secondIndex, m, c)) :
counter = counter + 1
return counter
# Driver Code
arr = [ 1, 2, 3, 4, 2 ]
n = len(arr)
# equation of line is y = mx + c
m = 1
c = 1
print (findOrderedPoints(arr, n, m, c))
# This code is contributed by Manish Shaw
# (manishshaw1)
C#
770
Chapter 141. Number of ordered points pair satisfying line equation
PHP
<?php
771
Chapter 141. Number of ordered points pair satisfying line equation
772
Chapter 141. Number of ordered points pair satisfying line equation
Output :
773
Chapter 141. Number of ordered points pair satisfying line equation
774
Chapter 141. Number of ordered points pair satisfying line equation
Output:
775
Chapter 142
Examples:
Input : n = 3, m = 2
Output : 3
2 parallelograms of size 1x1 and 1 parallelogram
of size 2x1.
776
Chapter 142. Number of parallelograms when n horizontal parallel lines intersect m
vertical parallellines
Input : n = 5, m = 5
Output : 100
The idea is to use Combination, which state, number of ways to choose k items from given
n items is given by n Cr .
To form a parallelogram, we need two horizontal parallel lines and two vertical parallel lines.
So, number of ways to choose two horizontal parallel lines are n C2 and number of ways to
choose two vertical parallel lines are m C2 . So, total number of possible parallelogram will
be n C2 x m C2 .
Below is C++ implementation of this approach:
C++
777
Chapter 142. Number of parallelograms when n horizontal parallel lines intersect m
vertical parallellines
Java
778
Chapter 142. Number of parallelograms when n horizontal parallel lines intersect m
vertical parallellines
return C[n][2] * C[m][2];
}
// Driver code
public static void main(String arg[])
{
int n = 5, m = 5;
System.out.println(countParallelogram(n, m));
}
}
// This code is contributed By Anant Agarwal.
C#
779
Chapter 142. Number of parallelograms when n horizontal parallel lines intersect m
vertical parallellines
Output:
100
Source
https://www.geeksforgeeks.org/number-of-parallelograms-when-n-horizontal-parallel-lines-intersect-m-vertical-para
780
Chapter 143
Number of possible pairs of Hypotenuse and Area to form right angled triangle - Geeks-
forGeeks
Given two arrays H and S. The array H[] contains the length of the hypotenuse and the
array S[] contains Area of a right-angled triangle. The task is to find all possible pairs of
(H, S) such that we can construct a right-angled triangle with hypotenuse H and area S.
Examples:
Say,
= Base of Right Angled Triangle
= Height of the Right Angled Triangle
Therefore,
area S = (a*b)/2
or, 4*S*S=a*a*b*b
781
Chapter 143. Number of possible pairs of Hypotenuse and Area to form right angled
triangle
Also,
a2 + b2 = H2
Therefore,
4*S2 = a2(H2-a2)
Solving this quadratic equation in a2 and putting discriminant>=0 (condition for a to exist).
We will get,
H2 >= 4*S
Naive Approach: The naive approach is to find all possible pairs of (H,S) and check if they
satisfy the condition, H2 >= 4*S. Count the number of pairs which satisfies this condition
and print the count.
Below is the implementation of the naive approach:
C++
#include <iostream>
using namespace std;
// Function to check the condition
bool check(int H, int S)
{
// Condition for triangle to exist
return H * H >= 4 * S;
}
// Function to find all pairs
int findPairs(int H[], int n, int S[], int m)
{
int count = 0;
// Checking all possible pairs
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
if (check(H[i], S[j]))
count++;
782
Chapter 143. Number of possible pairs of Hypotenuse and Area to form right angled
triangle
}
}
return count;
}
// Driver code
int main()
{
int H[] = { 1, 6, 4 };
int n = sizeof(H)/sizeof(H[0]);
int S[] = { 23, 3, 42, 14 };
int m = sizeof(S)/sizeof(S[0]);
cout<<findPairs(H, n, S, m);
return 0;
}
Java
class GFG
{
// Function to check the condition
static boolean check(int H, int S)
{
// Condition for triangle to exist
return H * H >= 4 * S;
}
// Function to find all pairs
static int findPairs(int H[], int n,
int S[], int m)
{
int count = 0;
// Checkinag all possible pairs
for (int i = 0; i < n; i++)
{
for (int j = 0; j < m; j++)
{
if (check(H[i], S[j]))
count++;
}
}
783
Chapter 143. Number of possible pairs of Hypotenuse and Area to form right angled
triangle
return count;
}
// Driver code
public static void main(String args[])
{
int H[] = { 1, 6, 4 };
int n = H.length;
int S[] = { 23, 3, 42, 14 };
int m = S.length;
System.out.println(findPairs(H, n, S, m));
}
}
// This code is contributed
// by ankita_saini
Python3
# Python 3 implementation
# of above approach
# Function to check the condition
def check(H, S) :
# Condition for triangle to exist
return H * H >= 4 * S
# Function to find all pairs
def findPairs(H, n, S, m):
count = 0
# Checking all possible pairs
for i in range(n) :
for j in range(m) :
if check(H[i], S[j]) :
count += 1
return count
# Driver Code
if __name__ == "__main__" :
H = [ 1, 6, 4]
n = len(H)
784
Chapter 143. Number of possible pairs of Hypotenuse and Area to form right angled
triangle
S = [ 23, 3, 42, 14]
m = len(S)
# function calling
print(findPairs(H, n, S,m))
# This code is contributed by ANKITRAI1
Output:
Efficient Approach: An efficient approach is to sort both the arrays available in increasing
order. Then, for every possible length of the hypotenuse, apply Binary search to find the
maximum area which satisfies the necessary condition.
Say, after the Binary search maximum possible area is available at index 4 in the array S[].
Then we can form 4 such possible pairs since all area less than that at index 4 will also be
satisfying the condition.
Below is the implementation of the efficient approach:
C++
#include <bits/stdc++.h>
using namespace std;
// Function to check the condition
bool check(int H, int S)
{
// Condition for triangle to exist
return H * H >= 4 * S;
}
// Function to find all pairs
int findPairs(int H[], int n, int S[], int m)
{
int count = 0;
// Sort both the arrays
sort(H, H + n);
sort(S, S + m);
// To keep track of last possible Area
int index = -1;
785
Chapter 143. Number of possible pairs of Hypotenuse and Area to form right angled
triangle
Output:
786
Chapter 143. Number of possible pairs of Hypotenuse and Area to form right angled
triangle
Source
https://www.geeksforgeeks.org/number-of-possible-pairs-of-hypotenuse-and-area-to-form-right-angled-triangle/
787
Chapter 144
Number of quadrilaterals
possible from the given points
Approach:
788
Chapter 144. Number of quadrilaterals possible from the given points
1. We need to check whether any of the given points are same. If yes, no of quadri-
lateral = 0
2. Then we need to check whether any of the 3 points of the given 4 points are collinear
or not. If yes, no of quadrilateral=0.Check Program to check if three points are
collinear link to check collinearity of 3 points.
3. (a) if its a convex quadrilateral then there is only one possible quadrilateral.
(b) if its a concave quadrilateral then there are 3 possible quadrilaterals.
This can be determined by How to check if two given line segments intersect? of diagonals.
In case of a convex quadrilateral, the diagonals will intersect whereas in case of a concave
quadrilateral the diagonals won’t intersect.
since we don’t know the orientation of the points, we can’t specifically determine the diag-
onals so all the distinct line segments(no common points in the two line segments) of the
quadrilateral and determine whether they intersect or not.
Refer to the figure to understand how to determine the type of quadrilateral :
Convex quadrilateral:
Concave quadrilateral
789
Chapter 144. Number of quadrilaterals possible from the given points
C++
#include <iostream>
using namespace std;
struct Point // points
{
int x;
int y;
};
// determines the orientation of points
int orientation(Point p, Point q, Point r)
{
int val = (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y);
if (val == 0)
return 0;
return (val > 0) ? 1 : 2;
}
// check whether the distinct line segments intersect
bool doIntersect(Point p1, Point q1, Point p2, Point q2)
{
int o1 = orientation(p1, q1, p2);
int o2 = orientation(p1, q1, q2);
int o3 = orientation(p2, q2, p1);
int o4 = orientation(p2, q2, q1);
if (o1 != o2 && o3 != o4)
return true;
return false;
}
// check if points overlap(similar)
bool similar(Point p1, Point p2)
{
// it is same, we are returning false because
// quadrilateral is not possible in this case
if (p1.x == p2.x && p1.y == p2.y)
return false;
// it is not same, So there is a
790
Chapter 144. Number of quadrilaterals possible from the given points
791
Chapter 144. Number of quadrilaterals possible from the given points
return 0;
//** Checking for cases where no of quadrilaterals= 1 or 3 **
int check = 0;
if (doIntersect(p1, p2, p3, p4))
check = 1;
if (doIntersect(p1, p3, p2, p4))
check = 1;
if (doIntersect(p1, p2, p4, p3))
check = 1;
if (check == 0)
return 3;
return 1;
}
// Driver code
int main()
{
struct Point p1, p2, p3, p4;
// A =(0, 9), B = (-1, 0), C = (5, -1), D=(5, 9)
p1.x = 0, p1.y = 9;
p2.x = -1, p2.y = 0;
p3.x = 5, p3.y = -1;
p4.x = 5, p4.y = 9;
cout << no_of_quads(p1, p2, p3, p4) << endl;
// A=(0, 9), B=(-1, 0), C=(5, -1), D=(0, 3)
p1.x = 0, p1.y = 9;
p2.x = -1, p2.y = 0;
p3.x = 5, p3.y = -1;
p4.x = 0, p4.y = 3;
cout << no_of_quads(p1, p2, p3, p4) << endl;
// A=(0, 9), B=(0, 10), C=(0, 11), D=(0, 12)
p1.x = 0, p1.y = 9;
p2.x = 0, p2.y = 10;
p3.x = 0, p3.y = 11;
p4.x = 0, p4.y = 12;
cout << no_of_quads(p1, p2, p3, p4) << endl;
// A=(0, 9), B=(0, 9), C=(5, -1), D=(0, 3)
p1.x = 0, p1.y = 9;
p2.x = 0, p2.y = 9;
p3.x = 5, p3.y = -1;
p4.x = 0, p4.y = 3;
792
Chapter 144. Number of quadrilaterals possible from the given points
Java
class GFG
{
static class Point // points
{
int x;
int y;
}
// determines the orientation of points
static int orientation(Point p, Point q,
Point r)
{
int val = (q.y - p.y) * (r.x - q.x) -
(q.x - p.x) * (r.y - q.y);
if (val == 0)
return 0;
return (val > 0) ? 1 : 2;
}
// check whether the distinct
// line segments intersect
static boolean doIntersect(Point p1, Point q1,
Point p2, Point q2)
{
int o1 = orientation(p1, q1, p2);
int o2 = orientation(p1, q1, q2);
int o3 = orientation(p2, q2, p1);
int o4 = orientation(p2, q2, q1);
if (o1 != o2 && o3 != o4)
return true;
return false;
}
// check if points overlap(similar)
static boolean similar(Point p1, Point p2)
{
// it is same, we are returning
793
Chapter 144. Number of quadrilaterals possible from the given points
794
Chapter 144. Number of quadrilaterals possible from the given points
795
Chapter 144. Number of quadrilaterals possible from the given points
// A=(0, 9), B=(-1, 0),
// C=(5, -1), D=(0, 3)
p1.x = 0; p1.y = 9;
p2.x = -1; p2.y = 0;
p3.x = 5; p3.y = -1;
p4.x = 0; p4.y = 3;
System.out.println(no_of_quads(p1, p2, p3, p4));
// A=(0, 9), B=(0, 10),
// C=(0, 11), D=(0, 12)
p1.x = 0; p1.y = 9;
p2.x = 0; p2.y = 10;
p3.x = 0; p3.y = 11;
p4.x = 0; p4.y = 12;
System.out.println(no_of_quads(p1, p2, p3, p4));
// A=(0, 9), B=(0, 9),
// C=(5, -1), D=(0, 3)
p1.x = 0; p1.y = 9;
p2.x = 0; p2.y = 9;
p3.x = 5; p3.y = -1;
p4.x = 0; p4.y = 3;
System.out.println(no_of_quads(p1, p2, p3, p4));
}
}
// This code is contributed
// by Arnab Kundu
Output:
1
3
0
0
Improved By : andrew1234
Source
https://www.geeksforgeeks.org/number-of-quadrilaterals-possible-from-the-given-points/
796
Chapter 145
Input : N = 2, M = 2
Output : 9
There are 4 rectangles of size 1 x 1.
There are 2 rectangles of size 1 x 2
There are 2 rectangles of size 2 x 1
There is one rectangle of size 1 x 1.
Input : N = 5, M = 4
Output : 150
Input : N = 4, M = 3
Output: 60
797
Chapter 145. Number of rectangles in N*M grid
C++
Java
798
Chapter 145. Number of rectangles in N*M grid
// This code is contributed by Arnav Kr. Mandal.
Python3
C#
PHP
<?php
// PHP program to count
// number of rectangles
799
Chapter 145. Number of rectangles in N*M grid
// in a n x m grid
function rectCount($n, $m)
{
return ($m * $n *
($n + 1) *
($m + 1)) / 4;
}
// Driver Code
$n = 5;
$m = 4;
echo rectCount($n, $m);
// This code is contributed
// by ajit
?>
Output:
150
Improved By : jit_t
Source
https://www.geeksforgeeks.org/number-rectangles-nm-grid/
800
Chapter 146
Input: R = 2
Output: 8
8 rectangles can be cut from a circular sheet of radius 2.
These are: 1×1, 1×2, 2×1, 2×2, 1×3, 3×1, 2×3, 3×2.
Input: R = 1
Output: 1
Only one rectangle with dimensions 1 X 1 is possible.
Approach
Consider the following diagram,
801
Chapter 146. Number of rectangles in a circle of radius R
Its easy to see, that ABCD is the largest rectangle that can be formed in the given circle
with radius R and centre O, having dimensions a X b
Drop a perpendicular AO such that, �AOD = �AOB = 90°
Consider the following diagram for further analysis,
802
Chapter 146. Number of rectangles in a circle of radius R
803
Chapter 146. Number of rectangles in a circle of radius R
The diameter BD is the maximum diagonal the rectangle can have to be able to be cut from
the Circular Sheet.
Thus, all the combinations of a and b can be checked to form all possible rectangles, and if
the diagonal of any such rectangle is less than or equal to the length of the diagonal of the
largest rectangle formed (i.e 2 * R, where R is the Radius of the circle as explained above)
Now, the maximum length of a and b will always be strictly less than the diameter of the
circle so all possible values of a and b will lie in the closed interval [1, (2 * R – 1)].
Below is the implementation of the above approach:
C++
804
Chapter 146. Number of rectangles in a circle of radius R
}
return rectangles;
}
// Driver Code
int main()
{
// Radius of the circle
int radius = 2;
int totalRectangles;
totalRectangles = countRectangles(radius);
cout << totalRectangles << " rectangles can be"
<< "cut from a circle of Radius " << radius;
return 0;
}
Java
805
Chapter 146. Number of rectangles in a circle of radius R
806
Chapter 146. Number of rectangles in a circle of radius R
// by anuj_67.
Python3
807
Chapter 146. Number of rectangles in a circle of radius R
C#
808
Chapter 146. Number of rectangles in a circle of radius R
int diagnalLengthSquare = (a * a +
b * b);
// If this rectangle's
// Diagonal Length is
// less than the Diameter,
// it is a valid rectangle,
// thus increment counter
if (diagnalLengthSquare <=
diameterSquare)
{
rectangles++;
}
}
}
return rectangles;
}
// Driver Code
public static void Main ()
{
// Radius of the circle
int radius = 2;
int totalRectangles;
totalRectangles = countRectangles(radius);
Console.WriteLine(totalRectangles +
" rectangles can be " +
"cut from a circle of" +
" Radius " + radius);
}
}
// This code is contributed
// by anuj_67.
PHP
<?php
// PHP program to find the
// number of rectangles that
// can be cut from a circle
// of Radius R
// Function to return the
// total possible rectangles
809
Chapter 146. Number of rectangles in a circle of radius R
810
Chapter 146. Number of rectangles in a circle of radius R
$totalRectangles;
$totalRectangles = countRectangles($radius);
echo $totalRectangles , " rectangles can be " ,
"cut from a circle of Radius " , $radius;
// This code is contributed
// by anuj_67.
?>
Output:
Source
https://www.geeksforgeeks.org/number-of-rectangles-in-a-circle-of-radius-r/
811
Chapter 147
Input: 9 6
Output: 6
Rectangle can be cut into squares of size 3.
Input: 4 2
Output: 2
Rectangle can be cut into squares of size 2.
Approach: The task is to cut the rectangle in squares with the side of length s without
pieces of the rectangle left over, so s must divide both m and n. Also, the side of the
square should be maximum possible, therefore, s should be the greatest common divisor of
m and n.
so, s = gcd(m, n).
To find the number of squares the rectangle is cut into, the task to be done is to divide the
area of a rectangle with an area of the square of size s.
C++
812
Chapter 147. Number of squares of maximum area in a rectangle
#include <bits/stdc++.h>
using namespace std;
// Function to find number of squares
int NumberOfSquares(int x, int y)
{
// Here in built c++ gcd function is used
int s = __gcd(x, y);
int ans = (x * y) / (s * s);
return ans;
}
// Driver code
int main()
{
int m = 385, n = 60;
// Call the function NumberOfSquares
cout << NumberOfSquares(m, n);
return 0;
}
Java
813
Chapter 147. Number of squares of maximum area in a rectangle
Python3
814
Chapter 147. Number of squares of maximum area in a rectangle
# a is greater
if (a > b):
return __gcd(a - b, b);
return __gcd(a, b - a);
# Function to find
# number of squares
def NumberOfSquares(x, y):
# Here in built PHP
# gcd function is used
s = __gcd(x, y);
ans = (x * y) / (s * s);
return int(ans);
# Driver Code
m = 385;
n = 60;
# Call the function
# NumberOfSquares
print(NumberOfSquares(m, n));
# This code is contributed
# by mit
C#
815
Chapter 147. Number of squares of maximum area in a rectangle
// a is greater
if (a > b)
return __gcd(a - b, b);
return __gcd(a, b - a);
}
// Function to find
// number of squares
static int NumberOfSquares(int x,
int y)
{
// Here in built c++
// gcd function is used
int s = __gcd(x, y);
int ans = (x * y) /
(s * s);
return ans;
}
// Driver Code
static public void Main ()
{
int m = 385, n = 60;
// Call the function
// NumberOfSquares
Console.WriteLine(NumberOfSquares(m, n));
}
}
// This code is contributed by ajit
PHP
<?php
// PHP code for calculating
// the number of squares
// Recursive function to
// return gcd of a and b
function __gcd($a, $b)
{
// Everything divides 0
if ($a == 0 || $b == 0)
816
Chapter 147. Number of squares of maximum area in a rectangle
return 0;
// base case
if ($a == $b)
return $a;
// a is greater
if ($a > $b)
return __gcd($a - $b, $b);
return __gcd($a, $b - $a);
}
// Function to find
// number of squares
function NumberOfSquares($x, $y)
{
// Here in built PHP
// gcd function is used
$s = __gcd($x, $y);
$ans = ($x * $y) /
($s * $s);
return $ans;
}
// Driver Code
$m = 385;
$n = 60;
// Call the function
// NumberOfSquares
echo (NumberOfSquares($m, $n));
// This code is contributed
// by akt_mit
?>
Output:
924
Source
https://www.geeksforgeeks.org/number-of-squares-of-maximum-area-in-a-rectangle/
817
Chapter 148
Number of triangles in a plane if no more than two points are collinear - GeeksforGeeks
Given n points in a plane and no more than two points are collinear, the task is to count
the number of triangles in a given plane.
Examples:
Input : n = 3
Output : 1
Input : n = 4
Output : 4
818
Chapter 148. Number of triangles in a plane if no more than two points are collinear
Let there are n points in a plane and no three or more points are collinear then number of
C++
819
Chapter 148. Number of triangles in a plane if no more than two points are collinear
Java
820
Chapter 148. Number of triangles in a plane if no more than two points are collinear
countNumberOfTriangles(n));
}
}
Python3
C#
821
Chapter 148. Number of triangles in a plane if no more than two points are collinear
// Formula to find number
// of triangle
// nC3 = n * (n - 1) *
// (n - 2) / 6
return n * (n - 1) *
(n - 2) / 6;
}
// Driver code
public static void Main()
{
int n = 4;
Console.WriteLine(
countNumberOfTriangles(n));
}
}
// This code is contributed by anuj_67.
PHP
<?php
// PHP program to find the
// number of triangles in a
// plane if no more then
// two points are collinear.
// Function to find number
// of triangles in a plane.
function countNumberOfTriangles($n)
{
// Formula to find number
// of triangles nC3 = n *
// (n - 1) * (n - 2) / 6
return $n * ($n - 1) *
($n - 2) / 6;
}
// Driver code
$n = 4;
echo countNumberOfTriangles($n);
// This code is contributed
// by anuj_67.
?>
822
Chapter 148. Number of triangles in a plane if no more than two points are collinear
Output:
Source
https://www.geeksforgeeks.org/number-of-triangles-in-a-plane-if-no-more-than-two-points-are-collinear/
823
Chapter 149
Examples :
Input : N = 4
Output : 5
We can make following five rectangles
1 x 1, 1 x 2, 2 x 2, 1 x 3 and 1 x 4
824
Chapter 149. Number of unique rectangles formed using N unit squares
Input : N = 5
Output : 6
Input : 6
Output : 8
C++
Java
825
Chapter 149. Number of unique rectangles formed using N unit squares
Python3
# Python3 program to count rotationally
# equivalent rectangles with n unit squares
import math
def countRect(n):
ans = 0
for length in range(1, int(math.sqrt(n)) + 1):
height = length
while(height * length <= n):
# height >= length is maintained
ans += 1
height += 1
return ans
# Driver code
826
Chapter 149. Number of unique rectangles formed using N unit squares
n = 5
print(countRect(n))
# This code is contributed by Anant Agarwal.
C#
PHP
<?php
// PHP program to count
// rotationally equivalent
// rectangles with n unit squares
function countRect($n)
{
827
Chapter 149. Number of unique rectangles formed using N unit squares
$ans = 0;
for ($length = 1;
$length <= sqrt($n); $length++)
for ($height = $length;
$height * $length <= $n; $height++)
// height >= length is maintained
$ans++;
return $ans;
}
// Driver code
$n = 5;
echo countRect($n);
// This code is contributed by @ajit
?>
Output :
Improved By : jit_t
Source
https://www.geeksforgeeks.org/number-unique-rectangles-formed-using-n-unit-squares/
828
Chapter 150
If we take one point on given line at infinite distance then total distance cost will be infinite,
now when we move this point on line towards given points the total distance cost starts
decreasing and after some time, it again starts increasing which reached to infinite on the
other infinite end of line so distance cost curve looks like a U-curve and we have to find the
bottom value of this U-curve.
As U-curve is not monotonically increasing or decreasing we can’t use binary search for
finding bottom most point, here we will use ternary search for finding bottom most point,
ternary search skips one third of search space at each iteration, you can read more about
ternary search here.
So solution proceeds as follows, we start with low and high initialized as some smallest and
largest values respectively, then we start iteration, in each iteration we calculate two mids,
mid1 and mid2, which represent 1/3rd and 2/3rd position in search space, we calculate
total distance of all points with mid1 and mid2 and update low or high by comparing these
distance cost, this iteration continues untill low and high become approximately equal.
829
Chapter 150. Optimum location of point to minimize total distance
#include <bits/stdc++.h>
using namespace std;
#define sq(x) ((x)*(x))
#define EPS 1e-6
#define N 5
// structure defining a point
struct point
{
int x, y;
point() {}
point(int x, int y) : x(x), y(y) {}
};
// structure defining a line of ax + by + c = 0 form
struct line
{
int a, b, c;
line(int a, int b, int c) : a(a), b(b), c(c) {}
};
// method to get distance of point (x, y) from point p
double dist(double x, double y, point p)
{
return sqrt(sq(x - p.x) + sq(y - p.y));
}
/* Utility method to compute total distance all points
when choose point on given line has x-cordinate
value as X */
double compute(point p[], int n, line l, double X)
{
double res = 0;
// calculating Y of choosen point by line equation
double Y = -1 * (l.c + l.a*X) / l.b;
for (int i = 0; i < n; i++)
res += dist(X, Y, p[i]);
return res;
}
// Utility method to find minimum total distance
double findOptimumCostUtil(point p[], int n, line l)
{
double low = -1e6;
double high = 1e6;
830
Chapter 150. Optimum location of point to minimize total distance
831
Chapter 150. Optimum location of point to minimize total distance
return 0;
}
Output:
20.7652
Source
https://www.geeksforgeeks.org/optimum-location-point-minimize-total-distance/
832
Chapter 151
• counterclockwise
• clockwise
• colinear
If orientation of (p1, p2, p3) is collinear, then orientation of (p3, p2, p1) is also collinear.
If orientation of (p1, p2, p3) is clockwise, then orientation of (p3, p2, p1) is counterclockwise
and vice versa is also true.
Given three points p1, p2 and p3, find orientation of (p1, p2, p3).
Example:
833
Chapter 151. Orientation of 3 ordered points
C++
834
Chapter 151. Orientation of 3 ordered points
return (val > 0)? 1: 2; // clock or counterclock wise
}
// Driver program to test above functions
int main()
{
Point p1 = {0, 0}, p2 = {4, 4}, p3 = {1, 2};
int o = orientation(p1, p2, p3);
if (o==0) cout << "Linear";
else if (o == 1) cout << "Clockwise";
else cout << "CounterClockwise";
return 0;
}
Java
835
Chapter 151. Orientation of 3 ordered points
}
/* Driver program to test above function */
public static void main(String[] args)
{
Point p1 = new Point(0, 0);
Point p2 = new Point(4, 4);
Point p3 = new Point(1, 2);
int o = orientation(p1, p2, p3);
if (o==0)
System.out.print("Linear");
else if (o == 1)
System.out.print("Clockwise");
else
System.out.print("CounterClockwise");
}
}
//This code is contributed by Arnav Kr. Mandal.
Output:
CounterClockwise
Source
https://www.geeksforgeeks.org/orientation-3-ordered-points/
836
Chapter 152
Input : 13 x 29
Output : 9
Explanation :
2 (squares of size 13x13) +
4 (squares of size 3x3) +
3 (squares of size 1x1)=9
Input : 4 x 5
Output : 5
Explanation :
1 (squares of size 4x4) +
4 (squares of size 1x1)
We know that if we want to cut minimum number of squares from the paper then we would
have to cut largest square possible from the paper first and largest square will have same
side as smaller side of the paper. For example if paper have the size 13 x 29, then maximum
square will be of side 13. so we can cut 2 square of size 13 x 13 (29/13 = 2). Now remaining
paper will have size 3 x 13. Similarly we can cut remaining paper by using 4 squares of size
3 x 3 and 3 squares of 1 x 1. So minimum 9 squares can be cut from the Paper of size 13 x
29.
837
Chapter 152. Paper Cut into Minimum Number of Squares
C++
838
Chapter 152. Paper Cut into Minimum Number of Squares
b = rem;
}
return result;
}
// Driver code
int main()
{
int n = 13, m = 29;
cout << minimumSquare(n, m);
return 0;
}
Java
839
Chapter 152. Paper Cut into Minimum Number of Squares
return result;
}
// Driver code
public static void main(String[] args)
{
int n = 13, m = 29;
System.out.println(minimumSquare(n, m));
}
}
//This code is contributed by Smitha Dinesh Semwal.
Python3
840
Chapter 152. Paper Cut into Minimum Number of Squares
Output:
Note that the above Greedy solution doesn’t always produce optimal result. For
example if input is 36 x 30, the above algorithm would produce output 6, but we can cut
the paper in 5 squares
1) Three squares of size 12 x 12
2) Two squares of size 18 x 18.
Thanks to Sergey V. Pereslavtsev for pointing out the above case.
Source
https://www.geeksforgeeks.org/paper-cut-minimum-number-squares/
841
Chapter 153
Input1 : m = 5, n = 5, k = 2, r = 1,
X = {1, 3}, Y = {3, 3}
Output1 : Possible
Input2 : m = 5, n = 5, k = 2, r = 1,
X = {1, 1}, Y = {2, 3}.
Output2 : Not Possible
Approach : Check if the centre of a cell (i, j) of the rectangle comes within any of the
circles then do not traverse through that cell and mark that as ‘blocked’. Mark rest of the
cells initially as ‘unvisited’. Then use BFS to find out shortest path of each cell from starting
position. If the end cell is visited then we will return “Possible” otherwise “Not Possible”.
Algorithm :
842
Chapter 153. Path in a Rectangle with Circles
3. Now, apply BFS from the starting cell and if a cell can be reached then change the
value of that cell to 1.
4. If the value of the ending cell is 1, then return ‘Possible’, otherwise return ‘Not Possi-
ble’.
C++
843
Chapter 153. Path in a Rectangle with Circles
844
Chapter 153. Path in a Rectangle with Circles
}
// check right cell
if ((eley > n - 1) &&
(rect[elex][eley + 1] == 0))
{
rect[elex][eley + 1] = 1;
vector<int> v = {elex, eley + 1};
qu.push_back(v);
}
// check bottom-left cell
if ((elex < m - 1) && (eley > 0) &&
(rect[elex + 1][eley - 1] == 0))
{
rect[elex + 1][eley - 1] = 1;
vector<int> v = {elex + 1, eley - 1};
qu.push_back(v);
}
// check bottom cell
if ((elex < m - 1) &&
(rect[elex + 1][eley] == 0))
{
rect[elex + 1][eley] = 1;
vector<int> v = {elex + 1, eley};
qu.push_back(v);
}
// check bottom-right cell
if ((elex < m - 1) && (eley < n - 1) &&
(rect[elex + 1][eley + 1] == 0))
{
rect[elex + 1][eley + 1] = 1;
vector<int> v = {elex + 1, eley + 1};
qu.push_back(v);
}
}
// Now if the end cell (i.e. bottom right cell)
// is 1(reachable) then we will send true.
return (rect[m - 1][n - 1] == 1);
}
// Driver Program
int main() {
// Test case 1
845
Chapter 153. Path in a Rectangle with Circles
int m1 = 5, n1 = 5, k1 = 2, r1 = 1;
vector<int> X1 = {1, 3};
vector<int> Y1 = {3, 3};
if (isPossible(m1, n1, k1, r1, X1, Y1))
cout << "Possible" << endl;
else
cout << "Not Possible" << endl;
// Test case 2
int m2 = 5, n2 = 5, k2 = 2, r2 = 1;
vector<int> X2 = {1, 1};
vector<int> Y2 = {2, 3};
if (isPossible(m2, n2, k2, r2, X2, Y2))
cout << "Possible" << endl;
else
cout << "Not Possible" << endl;
return 0;
}
Output:
Possible
Not Possible
Time Complexity : It takes O(m*n*k) time to compute whether a cell is within or not
in any circle. And it takes O(V+E) time in BFS. Here, number of edges in m*n grid is
m*(n-1)+n*(m-1) and vertices m*n. So it takes O(m*n) time in DFS. Hence, the time
complexity is O(m*n*k). The complexity can be improved if we iterate through each circles
and mark -1 the cells which are coming within it.
Source
https://www.geeksforgeeks.org/path-rectangle-containing-circles/
846
Chapter 154
Input : n = 3
Output : 18
Input : n = 7
Output : 196
847
Chapter 154. Pentagonal Pyramidal Number
int sum = 0;
// Running loop from 1 to n
for (int i = 1; i <= n; i++) {
// get nth pentagonal number
int p = (3 * i * i - i) / 2;
// add to sum
sum = sum + p;
}
return sum;
}
// Driver Program
int main()
{
int n = 4;
cout << pentagon_pyramidal(n) << endl;
return 0;
}
Java
848
Chapter 154. Pentagonal Pyramidal Number
}
// Driver Code
public static void main (String[] args)
{
int n = 4;
System.out.println(pentagon_pyramidal(n));
}
}
// This code is contributed by anuj_67.
Python3
C#
849
Chapter 154. Pentagonal Pyramidal Number
PHP
<?php
// PHP Program to get nth
// Pentagonal pyramidal number.
// function to get nth
// Pentagonal pyramidal number.
function pentagon_pyramidal($n)
{
$sum = 0;
// Running loop from 1 to n
for ($i = 1; $i <= $n; $i++)
{
// get nth pentagonal number
$p = (3 * $i *
850
Chapter 154. Pentagonal Pyramidal Number
$i - $i) / 2;
// add to sum
$sum = $sum + $p;
}
return $sum;
}
// Driver Code
$n = 4;
echo pentagon_pyramidal($n);
// This code is contributed by m_kit
?>
Output :
40
C++
851
Chapter 154. Pentagonal Pyramidal Number
return 0;
}
Java
Python3
C#
852
Chapter 154. Pentagonal Pyramidal Number
PHP
<?php
// PHP Program to get
// nth Pentagonal
// pyramidal number.
// function to get
// nth Pentagonal
// pyramidal number.
function pentagon_pyramidal($n)
{
return $n * $n *
($n + 1) / 2;
}
// Driver Code
$n = 4;
echo pentagon_pyramidal($n);
853
Chapter 154. Pentagonal Pyramidal Number
Output :
40
Source
https://www.geeksforgeeks.org/pentagonal-pyramidal-number/
854
Chapter 155
Pentatope number
Input : 5
Output :70
Input :8
Output :1001
C++
855
Chapter 155. Pentatope number
{
return (n * (n + 1) * (n + 2) * (n + 3)) / 24;
}
// Drivers Code
int main()
{
// For 5th PentaTope Number
int n = 5;
cout << pentatopeNum(n) << endl;
// For 11th PentaTope Number
n = 11;
cout << pentatopeNum(n) << endl;
return 0;
}
Java
856
Chapter 155. Pentatope number
Python3
C#
857
Chapter 155. Pentatope number
PHP
<?php
// PHP Program to find the
// nth Pentatope Number
// Function that returns
// nth pentatope number
function pentatopeNum($n)
{
return ($n * ($n + 1) *
($n + 2) *
($n + 3)) / 24;
}
// Driver Code
// For 5th PentaTope Number
$n = 5;
echo pentatopeNum($n), "\n";
// For 11th PentaTope Number
$n = 11;
echo pentatopeNum($n), "\n" ;
// This code is contributed
// by aj_36
?>
Output :
70
1001
858
Chapter 155. Pentatope number
Reference:https://en.wikipedia.org/wiki/Pentatope_number
Improved By : jit_t, andrew1234
Source
https://www.geeksforgeeks.org/pentatope-number-2/
859
Chapter 156
Examples :
Input: x1 = 5, y1 = 6, a = -2, b = 3, c = 4
Output:3.32820117735
Input: x1 = -1, y1 = 3, a = 4, b = -3, c = – 5
Output:3.6
Approach: The distance (i.e shortest distance) from a given point to a line is the perpen-
dicular distance from that point to the given line. The equation of a line in the plane is
860
Chapter 156. Perpendicular distance between a point and a Line in 2 D
given by the equation ax + by + c = 0, where a, b and c are real constants. the co-ordinate
of the point is (x1, y1)
The formula for distance between a point and a line in 2-D is given by:
Java
861
Chapter 156. Perpendicular distance between a point and a Line in 2 D
Python
862
Chapter 156. Perpendicular distance between a point and a Line in 2 D
# Driver Code
x1 = 5
y1 = 6
a = -2
b = 3
c = 4
shortest_distance(x1, y1, a, b, c)
Output:
Program 2:
863
Chapter 156. Perpendicular distance between a point and a Line in 2 D
// This code is contributed
// by Amber_Saxena.
Python
Output:
Source
https://www.geeksforgeeks.org/perpendicular-distance-between-a-point-and-a-line-in-2-d/
864
Chapter 157
Input : 2
Output : 4
Input : 3
Output : 7
This problem is nothing but The Lazy Caterer’s Problemand has below formula.
Maximum number of pieces = 1 + n*(n+1)/2
Refer this for proof.
C++
865
Chapter 157. Pizza cut problem (Or Circle Division by Lines)
return 1 + n*(n+1)/2;
}
// Driver code
int main()
{
cout << findMaximumPieces(3);
return 0;
}
Java
C#
866
Chapter 157. Pizza cut problem (Or Circle Division by Lines)
// Driver Program to test above function
public static void Main()
{
Console.Write(findMaximumPieces(3));
}
}
// This code is contributed by nitin mittal.
PHP
<?php
// PHP program to find maximum
// no. of pieces by given
// number of cuts
// Function for finding maximum
// pieces with n cuts.
function findMaximumPieces($n)
{
return 1 + $n * ($n + 1) / 2;
}
// Driver code
echo findMaximumPieces(3);
// This code is contributed by nitin mittal.
?>
Output:
Source
https://www.geeksforgeeks.org/pizza-cut-problem-circle-division-lines/
867
Chapter 158
Polygon Clipping |
Sutherland–Hodgman
Algorithm
Example 2
Input : Polygon : (100,150), (200,250), (300,200)
Clipping Area : (100,300), (300,300), (200,100)
Output : (242, 185) (166, 166) (150, 200) (200, 250) (260, 220)
868
Chapter 158. Polygon Clipping | Sutherland–Hodgman Algorithm
1. Both vertices are inside : Only the second vertex is added to the output list
2. First vertex is outside while second one is inside : Both the point of intersection
of the edge with the clip boundary and the second vertex are added to the output list
3. First vertex is inside while second one is outside : Only the point of intersection
of the edge with the clip boundary is added to the output list
4. Both vertices are outside : No vertices are added to the output list
869
Chapter 158. Polygon Clipping | Sutherland–Hodgman Algorithm
There are two sub-problems that need to be discussed before implementing the algorithm:-
To decide if a point is inside or outside the clipper polygon
If the vertices of the clipper polygon are given in clockwise order then all the points lying
on the right side of the clipper edges are inside that polygon. This can be calculated using
870
Chapter 158. Polygon Clipping | Sutherland–Hodgman Algorithm
871
Chapter 158. Polygon Clipping | Sutherland–Hodgman Algorithm
// This functions clips all the edges w.r.t one clip
// edge of clipping area
void clip(int poly_points[][2], int &poly_size,
int x1, int y1, int x2, int y2)
{
int new_points[MAX_POINTS][2], new_poly_size = 0;
// (ix,iy),(kx,ky) are the co-ordinate values of
// the points
for (int i = 0; i < poly_size; i++)
{
// i and k form a line in polygon
int k = (i+1) % poly_size;
int ix = poly_points[i][0], iy = poly_points[i][1];
int kx = poly_points[k][0], ky = poly_points[k][1];
// Calculating position of first point
// w.r.t. clipper line
int i_pos = (x2-x1) * (iy-y1) - (y2-y1) * (ix-x1);
// Calculating position of second point
// w.r.t. clipper line
int k_pos = (x2-x1) * (ky-y1) - (y2-y1) * (kx-x1);
// Case 1 : When both points are inside
if (i_pos < 0 && k_pos < 0)
{
//Only second point is added
new_points[new_poly_size][0] = kx;
new_points[new_poly_size][1] = ky;
new_poly_size++;
}
// Case 2: When only first point is outside
else if (i_pos >= 0 && k_pos < 0)
{
// Point of intersection with edge
// and the second point is added
new_points[new_poly_size][0] = x_intersect(x1,
y1, x2, y2, ix, iy, kx, ky);
new_points[new_poly_size][1] = y_intersect(x1,
y1, x2, y2, ix, iy, kx, ky);
new_poly_size++;
new_points[new_poly_size][0] = kx;
new_points[new_poly_size][1] = ky;
new_poly_size++;
872
Chapter 158. Polygon Clipping | Sutherland–Hodgman Algorithm
}
// Case 3: When only second point is outside
else if (i_pos < 0 && k_pos >= 0)
{
//Only point of intersection with edge is added
new_points[new_poly_size][0] = x_intersect(x1,
y1, x2, y2, ix, iy, kx, ky);
new_points[new_poly_size][1] = y_intersect(x1,
y1, x2, y2, ix, iy, kx, ky);
new_poly_size++;
}
// Case 4: When both points are outside
else
{
//No points are added
}
}
// Copying new points into original array
// and changing the no. of vertices
poly_size = new_poly_size;
for (int i = 0; i < poly_size; i++)
{
poly_points[i][0] = new_points[i][0];
poly_points[i][1] = new_points[i][1];
}
}
// Implements Sutherland–Hodgman algorithm
void suthHodgClip(int poly_points[][2], int poly_size,
int clipper_points[][2], int clipper_size)
{
//i and k are two consecutive indexes
for (int i=0; i<clipper_size; i++)
{
int k = (i+1) % clipper_size;
// We pass the current array of vertices, it's size
// and the end points of the selected clipper line
clip(poly_points, poly_size, clipper_points[i][0],
clipper_points[i][1], clipper_points[k][0],
clipper_points[k][1]);
}
// Printing vertices of clipped polygon
for (int i=0; i < poly_size; i++)
873
Chapter 158. Polygon Clipping | Sutherland–Hodgman Algorithm
Output:
Related Articles:
Line Clipping | Set 1 (Cohen–Sutherland Algorithm)
Point Clipping Algorithm in Computer Graphics
Source
https://www.geeksforgeeks.org/polygon-clipping-sutherland-hodgman-algorithm-please-change-bmp-images-jpeg-pn
874
Chapter 159
Probability that the pieces of a broken stick form a n sided polygon - GeeksforGeeks
We have a stick of length L. The stick got broken at (n-1) randomly chosen points (lengths
of parts can be non-integer or floating point numbers also) so we get n parts. We need to
find the probability that these n pieces can form a n sided polygon.
Examples:
Input : L = 5 n = 3
Output : 0.25
We need to cut rope of length 5
into three parts.
First we need to find the condition when n lengths can form a n sided polygon. Let us
consider a triangle, we know for a triangle the length of the largest side must be smaller
than the sum of the lengths of other sides. Similarly for a n sided polygon the the length
of the largest side must be less than the sum of the other (n-1) sides. Why? Suppose we
break the stick into two equal halves. We further break one of the halves into (n-1) parts.
We can never place them such that they make a closed polygon. (Actually the best we can
do is to make 2 parallel lines). So we just need to find the probability that no part has the
length greater than or equal to L/2.
Now we need to work on the probability. There are many ways to calculate the required
probability we will use a geometric approach. Consider a circle of perimeter L. We place
n points on the perimeter. The probability that they lie on the same semicircle is .
Please refer this link for more information, let us denote it by P(E).
875
Chapter 159. Probability that the pieces of a broken stick form a n sided polygon
This probability is actually same as breaking the stick such that at least one part is
of length L/2. But we want just the complement of this event hence our answer is
C++
PHP
Output:
0.25
Source
https://www.geeksforgeeks.org/probability-that-the-pieces-of-a-broken-stick-form-a-n-sided-polygon/
876
Chapter 160
Examples:
Input : 4 5
Output : Area = 20
877
Chapter 160. Program for Area And Perimeter Of Rectangle
Perimeter = 18
Input : 2 3
Output : Area = 6
Perimeter = 10
Formulae :
C++
python
878
Chapter 160. Program for Area And Perimeter Of Rectangle
# Utility function
def areaRectangle(a, b):
return (a * b)
def perimeterRectangle(a, b):
return (2 * (a + b))
# Driver function
a = 5;
b = 6;
print ("Area = ", areaRectangle(a, b))
print ("Perimeter = ", perimeterRectangle(a, b))
# This code is contributed by 'saloni1297'.
Java
879
Chapter 160. Program for Area And Perimeter Of Rectangle
C#
PHP
<?php
// PHP program to find area
// and perimeter of rectangle
// Utility function
function areaRectangle( $a, $b)
880
Chapter 160. Program for Area And Perimeter Of Rectangle
{
$area = $a * $b;
return $area;
}
function perimeterRectangle( $a, $b)
{
$perimeter = 2 * ($a + $b);
return $perimeter;
}
// Driver program
$a = 5;
$b = 6;
echo("Area = " );
echo(areaRectangle($a, $b));
echo("\n");
echo( "Perimeter = ");
echo(perimeterRectangle($a, $b));
// This code is contributed by vt_m.
?>
Output :
Area = 30
Perimeter = 22
Improved By : vt_m
Source
https://www.geeksforgeeks.org/program-area-perimeter-rectangle/
881
Chapter 161
Examples :
Input : 4
Output :16
Input :8
Output :64
Formula
882
Chapter 161. Program for Area Of Square
C++
Java
Python3
883
Chapter 161. Program for Area Of Square
def areaSquare( side ):
area = side * side
return area
# Driver Code
side = 4
print(areaSquare(side))
# This code is contributed
# by "Sharad_Bhardwaj".
C#
// C# program to find
// the area of the square
using System;
class GFG
{
static int areaSquare(int side)
{
int area = side * side;
return area;
}
// Driver code
public static void Main()
{
int side = 4;
Console.WriteLine(areaSquare(side));
}
}
// This code is contributed by vt_m
PHP
<?php
// PHP program to find
// the aria of the square
function areaSquare($side)
{
$area = $side * $side;
return $area;
884
Chapter 161. Program for Area Of Square
}
// Driver Code
$side = 4;
echo(areaSquare($side));
// This code is contributed by Ajit.
?>
Output :
16
Source
https://www.geeksforgeeks.org/program-area-square/
885
Chapter 162
Input: a = 10, b = 8
Output: 36.00
The opposite sides of a parallelogram are of equal length and parallel. The angles are
pairwise equal but not necessarily 90 degree. The circumference of a Parallelogram can be
computed as sum of two adjacent sides each multiplied by 2.
886
Chapter 162. Program for Circumference of a Parallelogram
C++
Java
887
Chapter 162. Program for Circumference of a Parallelogram
Python3
C#
// C# Program To Calculate
// Circumference of a Parallelogram
using System;
888
Chapter 162. Program for Circumference of a Parallelogram
class GFG
{
static float circumferenceparallelogram(float a,
float b)
{
return ((2 * a) + (2 * b));
}
// Driver code
public static void Main()
{
float a = 10, b = 8;
Console.Write("Circumference of a" +
"given Parallelogram is :");
Console.Write(circumferenceparallelogram(a, b));
}
}
// This code is contributed by vt_m.
PHP
<?php
// PHP Program to calculate
// the Circumference of a
// Parallelogram.
function circumferenceparallelogram( $a, $b)
{
return ((2 * $a) + (2 * $b));
}
$a = 10; $b = 8;
echo "Circumference of a ".
"given Parallelogram is : ",
circumferenceparallelogram($a, $b);
// This code is contributed by anuuj_67.
?>
Output :
889
Chapter 162. Program for Circumference of a Parallelogram
Improved By : vt_m
Source
https://www.geeksforgeeks.org/program-circumference-parallelogram/
890
Chapter 163
First of all, let us assume that we have two points (x1 , y1 ) and (x2 , y2 ). Now, we find the
equation of line formed by these points.
Let the given lines be :
1. a1 x + b1 y = c1
2. a2 x + b2 y = c2
We have to now solve these 2 equations to find the point of intersection. To solve, we
multiply 1. by b2 and 2 by b1
This gives us,
891
Chapter 163. Program for Point of Intersection of Two Lines
a1 b2 x + b1 b2 y = c1 b2
a2 b1 x + b2 b1 y = c2 b1
Subtracting these we get,
(a1 b2 – a2 b1 ) x = c1 b2 – c2 b1
This gives us the value of x. Similarly, we can find the value of y. (x, y) gives us the point
of intersection.
Note: This gives the point of intersection of two lines, but if we are given line segments
instead of lines, we have to also recheck that the point so computed actually lies on both
the line segments.
If the line segment is specified by points (x1 , y1 ) and (x2 , y2 ), then to check if (x, y) is on
the segment we have to just check that
determinant = a1 b2 - a2 b1
if (determinant == 0)
{
// Lines are parallel
}
else
{
x = (c1b2 - c2b1)/determinant
y = (a1c2 - a2c1)/determinant
}
These can be derived by first getting the slope directly and then finding the intercept of
the line.
C++
892
Chapter 163. Program for Point of Intersection of Two Lines
void displayPoint(pdd P)
{
cout << "(" << P.first << ", " << P.second
<< ")" << endl;
}
pdd lineLineIntersection(pdd A, pdd B, pdd C, pdd D)
{
// Line AB represented as a1x + b1y = c1
double a1 = B.second - A.second;
double b1 = A.first - B.first;
double c1 = a1*(A.first) + b1*(A.second);
// Line CD represented as a2x + b2y = c2
double a2 = D.second - C.second;
double b2 = C.first - D.first;
double c2 = a2*(C.first)+ b2*(C.second);
double determinant = a1*b2 - a2*b1;
if (determinant == 0)
{
// The lines are parallel. This is simplified
// by returning a pair of FLT_MAX
return make_pair(FLT_MAX, FLT_MAX);
}
else
{
double x = (b2*c1 - b1*c2)/determinant;
double y = (a1*c2 - a2*c1)/determinant;
return make_pair(x, y);
}
}
// Driver code
int main()
{
pdd A = make_pair(1, 1);
pdd B = make_pair(4, 4);
pdd C = make_pair(1, 8);
pdd D = make_pair(2, 4);
pdd intersection = lineLineIntersection(A, B, C, D);
if (intersection.first == FLT_MAX &&
intersection.second==FLT_MAX)
{
cout << "The given lines AB and CD are parallel.\n";
893
Chapter 163. Program for Point of Intersection of Two Lines
}
else
{
// NOTE: Further check can be applied in case
// of line segments. Here, we have considered AB
// and CD as lines
cout << "The intersection of the given lines AB "
"and CD is: ";
displayPoint(intersection);
}
return 0;
}
Java
894
Chapter 163. Program for Point of Intersection of Two Lines
// Line CD represented as a2x + b2y = c2
double a2 = D.y - C.y;
double b2 = C.x - D.x;
double c2 = a2*(C.x)+ b2*(C.y);
double determinant = a1*b2 - a2*b1;
if (determinant == 0)
{
// The lines are parallel. This is simplified
// by returning a pair of FLT_MAX
return new Point(Double.MAX_VALUE, Double.MAX_VALUE);
}
else
{
double x = (b2*c1 - b1*c2)/determinant;
double y = (a1*c2 - a2*c1)/determinant;
return new Point(x, y);
}
}
// Driver method
public static void main(String args[])
{
Point A = new Point(1, 1);
Point B = new Point(4, 4);
Point C = new Point(1, 8);
Point D = new Point(2, 4);
Point intersection = lineLineIntersection(A, B, C, D);
if (intersection.x == Double.MAX_VALUE &&
intersection.y == Double.MAX_VALUE)
{
System.out.println("The given lines AB and CD are parallel.");
}
else
{
// NOTE: Further check can be applied in case
// of line segments. Here, we have considered AB
// and CD as lines
System.out.print("The intersection of the given lines AB" +
"and CD is: ");
Point.displayPoint(intersection);
}
}
895
Chapter 163. Program for Point of Intersection of Two Lines
Output:
Source
https://www.geeksforgeeks.org/program-for-point-of-intersection-of-two-lines/
896
Chapter 164
Input : 7
Output : 169.741
Input : 9
Output : 280.59
An regular octahedron has eight faces, which are all in the shape of equilateral triangles.The
area of an octahedron is 2 multiplied by the length of an edge squared multiplied by the
square root of three.
Formula:
Surface area= 2*(sqrt(3))*(side*side)
C++
897
Chapter 164. Program for Surface Area of Octahedron
{
return (2*(sqrt(3))*(side*side));
}
// Driver Function
int main()
{
double side = 7;
cout << "Surface area of octahedron ="
<< surface_area_octahedron(side)
<< endl;
}
Java
Python3
898
Chapter 164. Program for Surface Area of Octahedron
return (2*(math.sqrt(3))*(side*side))
# driver code
side = 7
print("Surface area of octahedron =" ,
surface_area_octahedron(side))
# This code is contributed by Gitanjali.
C#
// C# program to calculate
// surface area of Octahedron.
using System;
class GFG {
// utility Function
static double surface_area_octahedron(double side)
{
return (2 * (Math.Sqrt(3)) * (side * side));
}
// Driver code
public static void Main()
{
double side = 7;
Console.WriteLine("Surface area of octahedron ="
+ surface_area_octahedron(side));
}
}
// This code is contributed by vt_m.
PHP
<?php
// PHP Program to calculate
// surface area of Octahedron
// utility Function
function surface_area_octahedron($side)
{
return (2 * (sqrt(3)) *
($side * $side));
}
899
Chapter 164. Program for Surface Area of Octahedron
// Driver Code
$side = 7;
echo("Surface area of octahedron =");
echo( surface_area_octahedron($side));
// This code is contributed by vt_m.
?>
Output:
Improved By : vt_m
Source
https://www.geeksforgeeks.org/program-for-surface-area-of-octahedron/
900
Chapter 165
Examples:
901
Chapter 165. Program for Volume and Surface Area of Cube
Volume: a*a*a
Total Surface area: 6*a*a
C++
Java
902
Chapter 165. Program for Volume and Surface Area of Cube
// Driver code
public static void main (String[] args)
{
double a = 5;
System.out.println("Area = "+areaCube(a));
System.out.println("Total surface area = "
+surfaceCube(a));
}
}
// This code is contributed by Anant Agarwal.
Python3
C#
903
Chapter 165. Program for Volume and Surface Area of Cube
{
return (6 * a * a);
}
// Driver code
public static void Main()
{
double a = 5;
Console.WriteLine("Area = " + areaCube(a));
Console.WriteLine("Total surface area = "
+ surfaceCube(a));
}
}
// This code is contributed by vt_m.
PHP
<?php
// PHP program to find area
// and total surface area of cube
// utility fuction
function areaCube($a)
{
return ($a * $a * $a);
}
function surfaceCube( $a)
{
return (6 * $a * $a);
}
// driver function
$a = 5;
echo ("Area = ");
echo(areaCube($a));
echo("\n");
echo("Total surface area = ");
echo(surfaceCube($a));
// This code is contributed by vt_m.
?>
Output:
904
Chapter 165. Program for Volume and Surface Area of Cube
Area = 125
Total surface area = 150
Improved By : vt_m
Source
https://www.geeksforgeeks.org/program-volume-surface-area-cube/
905
Chapter 166
Examples :
Input : 2 3 4
Output : Area = 24
Total Surface Area = 52
Input : 5 6 12
Output : Area = 360
Total Surface Area = 324
906
Chapter 166. Program for Volume and Surface Area of Cuboid
Formulae :
Area = l*w*h
Total Surface Area = 2*l*w + 2*w*h + 2*l*h
where l, h, w are length, height and width of
cuboid respectively.
C++
Java
907
Chapter 166. Program for Volume and Surface Area of Cuboid
double w)
{
return (l * h * w);
}
static double surfaceAreaCuboid(double l, double h,
double w)
{
return (2 * l * w + 2 * w * h + 2 * l * h);
}
// Driver code
public static void main (String[] args)
{
double l = 1;
double h = 5;
double w = 7;
System.out.println("Area = " + areaCuboid(l, h, w));
System.out.println("Total Surface Area = "
+ surfaceAreaCuboid(l, h, w));
}
}
// This code is contributed By Anant Agarwal.
Python3
C#
908
Chapter 166. Program for Volume and Surface Area of Cuboid
PHP
<?php
// PHP program to find volume and
// total surface area of cuboid
// utility function
function areaCuboid($l, $h, $w)
{
return ($l * $h * $w);
}
function surfaceAreaCuboid($l, $h, $w)
{
return (2 * $l * $w + 2 * $w *
909
Chapter 166. Program for Volume and Surface Area of Cuboid
$h + 2 * $l * $h);
}
// Driver Code
$l = 1;
$h = 5;
$w = 7;
echo "Area = " ,
areaCuboid($l, $h, $w) , "\n";
echo "Total Surface Area = ",
surfaceAreaCuboid($l, $h, $w);
// This code is contributed by ajit
?>
Output :
Area = 35
Total Surface Area = 94
Improved By : jit_t
Source
https://www.geeksforgeeks.org/program-for-volume-and-surface-area-of-cuboid/
910
Chapter 167
The right circular cone after being cut by a plane parallel to its base results in a frustum as
follows:
911
Chapter 167. Program for Volume and Surface area of Frustum of Cone
where
r = radius of smaller circle
R = radius of bigger circle (or radius of base of the cone)
h = height of the frustum
where
r = radius of smaller circle
R = radius of bigger circle
l = slant height of the frustum
912
Chapter 167. Program for Volume and Surface area of Frustum of Cone
where
r = radius of smaller circle
R = radius of bigger circle
l = slant height of frustum
Examples:
Output :
Volume Of Frustum of Cone : 917.34436
Curved Surface Area Of Frustum of Cone : 267.03516
Total Surface Area Of Frustum of Cone : 735.1321
C++
913
Chapter 167. Program for Volume and Surface area of Frustum of Cone
// frustum of cone
float curved_surface_area(float r, float R, float l)
{
return pi * l * (R + r);
}
// Function to calculate Total Surface area of
// frustum of cone
float total_surface_area(float r, float R, float l,
float h)
{
return pi * l * (R + r) + pi * (r * r + R * R);
}
// Driver function
int main()
{
float small_radius = 3;
float big_radius = 8;
float slant_height = 13;
float height = 12;
// Printing value of volume and surface area
cout << "Volume Of Frustum of Cone : "
<< volume(small_radius, big_radius, height)
<< endl;
cout << "Curved Surface Area Of Frustum of Cone : "
<< curved_surface_area(small_radius, big_radius,
slant_height) << endl;
cout << "Total Surface Area Of Frustum of Cone : "
<< total_surface_area(small_radius, big_radius,
slant_height, height);
return 0;
}
Java
914
Chapter 167. Program for Volume and Surface area of Frustum of Cone
{
return (float)1 / 3 * pi * h * (r * r + R * R +
r * R);
}
// Function to calculate Curved Surface area of
// frustum of cone
public static float curved_surface_area(float r,
float R, float l)
{
return pi * l * (R + r);
}
// Function to calculate Total Surface area of
// frustum of cone
public static float total_surface_area(float r,
float R, float l, float h)
{
return pi * l * (R + r) + pi * (r * r + R * R);
}
// Driver function
public static void main(String args[])
{
float small_radius = 3;
float big_radius = 8;
float slant_height = 13;
float height = 12;
// Printing value of volume and surface area
System.out.print("Volume Of Frustum of Cone : ");
System.out.println(volume(small_radius,
big_radius, height));
System.out.print("Curved Surface Area Of" +
" Frustum of Cone : ");
System.out.println(curved_surface_area(small_radius,
big_radius, slant_height));
System.out.print("Total Surface Area Of" +
" Frustum of Cone : ");
System.out.println(total_surface_area(small_radius,
big_radius, slant_height, height));
}
}
Python3
915
Chapter 167. Program for Volume and Surface area of Frustum of Cone
916
Chapter 167. Program for Volume and Surface area of Frustum of Cone
C#
917
Chapter 167. Program for Volume and Surface area of Frustum of Cone
big_radius, height));
Console.Write("Curved Surface Area Of" +
" Frustum of Cone : ");
Console.WriteLine(curved_surface_area(small_radius,
big_radius, slant_height));
Console.Write("Total Surface Area Of" +
" Frustum of Cone : ");
Console.WriteLine(total_surface_area(small_radius,
big_radius, slant_height, height));
}
}
// This article is contributed by vt_m
PHP
<?php
// PHP program to calculate Volume and
// Surface area of frustum of cone
// Function to calculate
// Volume of frustum of cone
function volume($r, $R, $h)
{
$pi = 3.14159;
return (1 / (3)) * $pi * $h *
($r * $r + $R * $R + $r * $R);
}
// Function to calculate Curved
// Surface area of frustum of cone
function curved_surface_area($r, $R, $l)
{
$pi = 3.14159;
return $pi * $l * ($R + $r);
}
// Function to calculate Total Surface
// area of frustum of cone
function total_surface_area( $r, $R, $l, $h)
{
$pi = 3.14159;
return ($pi * $l * ($R + $r) +
$pi * ($r * $r + $R * $R));
918
Chapter 167. Program for Volume and Surface area of Frustum of Cone
}
// Driver Code
$small_radius = 3;
$big_radius = 8;
$slant_height = 13;
$height = 12;
// Printing value of volume
// and surface area
echo("Volume Of Frustum of Cone : ");
echo(volume($small_radius,
$big_radius,
$height));
echo("\n");
echo("Curved Surface Area Of Frustum of Cone : ");
echo (curved_surface_area($small_radius,
$big_radius ,
$slant_height));
echo("\n");
echo("Total Surface Area Of Frustum of Cone : ");
echo(total_surface_area($small_radius,
$big_radius,
$slant_height,
$height));
// This code is contributed by vt_m
?>
Output:
Improved By : vt_m
Source
https://www.geeksforgeeks.org/program-for-volume-and-surface-area-of-frustum-of-cone/
919
Chapter 168
920
Chapter 168. Program for distance between two points on earth
Longitude 2: -1.6997222222222223
Output: Distance is: 2.0043678382716137 Kilometers
Get the co-ordinates of point A in terms of latitude and longitude. Use the above conversion
method to convert the values of latitude and longitude in radians. I will call it as lat1 and
long1. Do the same for the co-ordinates of Point B and get lat2 and long2.
Now, to get the distance between point A and point B use the following formula:
The obtained distance, d, is in miles. If you want your value to to be in units of kilometers,
multiple d by 1.609344.
d in kilometers = 1.609344 * d in miles
Thus you can have the shortest distance between two places on Earth using the great circle
distance approach.
C++
921
Chapter 168. Program for distance between two points on earth
922
Chapter 168. Program for distance between two points on earth
{
long double lat1 = 53.32055555555556;
long double long1 = -1.7297222222222221;
long double lat2 = 53.31861111111111;
long double long2 = -1.6997222222222223;
// call the distance function
cout << setprecision(15) << fixed;
cout << distance(lat1, long1,
lat2, long2) << " K.M";
return 0;
}
// This code is contributed
// by Aayush Chaturvedi
Java
923
Chapter 168. Program for distance between two points on earth
Python3
924
Chapter 168. Program for distance between two points on earth
# driver code
lat1 = 53.32055555555556
lat2 = 53.31861111111111
lon1 = -1.7297222222222221
lon2 = -1.6997222222222223
print(distance(lat1, lat2, lon1, lon2), "K.M")
C#
// C# program to calculate
// Distance Between Two
// Points on Earth
using System;
class GFG
{
static double toRadians(
double angleIn10thofaDegree)
{
// Angle in 10th
// of a degree
return (angleIn10thofaDegree *
Math.PI) / 180;
}
static double distance(double lat1,
double lat2,
double lon1,
double lon2)
{
// The math module contains
// a function named toRadians
// which converts from degrees
// to radians.
lon1 = toRadians(lon1);
lon2 = toRadians(lon2);
lat1 = toRadians(lat1);
lat2 = toRadians(lat2);
// Haversine formula
double dlon = lon2 - lon1;
double dlat = lat2 - lat1;
double a = Math.Pow(Math.Sin(dlat / 2), 2) +
Math.Cos(lat1) * Math.Cos(lat2) *
Math.Pow(Math.Sin(dlon / 2),2);
double c = 2 * Math.Asin(Math.Sqrt(a));
925
Chapter 168. Program for distance between two points on earth
// Radius of earth in
// kilometers. Use 3956
// for miles
double r = 6371;
// calculate the result
return (c * r);
}
// Driver code
static void Main()
{
double lat1 = 53.32055555555556;
double lat2 = 53.31861111111111;
double lon1 = -1.7297222222222221;
double lon2 = -1.6997222222222223;
Console.WriteLine(distance(lat1, lat2,
lon1, lon2) + " K.M");
}
}
// This code is contributed by
// Manish Shaw(manishshaw1)
PHP
<?php
function twopoints_on_earth($latitudeFrom, $longitudeFrom,
$latitudeTo, $longitudeTo)
{
$long1 = deg2rad($longitudeFrom);
$long2 = deg2rad($longitudeTo);
$lat1 = deg2rad($latitudeFrom);
$lat2 = deg2rad($latitudeTo);
//Haversine Formula
$dlong = $long2 - $long1;
$dlati = $lat2 - $lat1;
$val = pow(sin($dlati/2),2)+cos($lat1)*cos($lat2)*pow(sin($dlong/2),2);
$res = 2 * asin(sqrt($val));
$radius = 3958.756;
return ($res*$radius);
926
Chapter 168. Program for distance between two points on earth
}
// latitude and longitude of Two Points
$latitudeFrom = 19.017656 ;
$longitudeFrom = 72.856178;
$latitudeTo = 40.7127;
$longitudeTo = -74.0059;
// Distance between Mumbai and New York
print_r(twopoints_on_earth( $latitudeFrom, $longitudeFrom,
$latitudeTo, $longitudeTo).' '.'miles');
// This code is contributed by akash1295
// https://auth.geeksforgeeks.org/user/akash1295/articles
?>
Output:
2.0043678382716137 K.M
Reference: Wikipedia
Improved By : Prasad_Kshirsagar, AayushChaturvedi, manishshaw1
Source
https://www.geeksforgeeks.org/program-distance-two-points-earth/
927
Chapter 169
C++
928
Chapter 169. Program for volume of Pyramid
// Function to find the
// volume of square pyramid
float volumeSquare(int b, int h)
{
float vol = (0.33) * b *
b * h;
return vol;
}
// Function to find the volume
// of pentagonal pyramid
float volumePentagonal(int a,
int b,
int h)
{
float vol = (0.83) * a * b * h;
return vol;
}
// Function to find the volume
// of hexagonal pyramid
float volumeHexagonal(int a,
int b,
int h)
{
float vol = a * b * h;
return vol;
}
// Driver Code
int main()
{
int b = 4, h = 9, a = 4;
cout << "Volume of triangular"
<< " base pyramid is "
<< volumeTriangular(a, b, h)
<< endl;
cout << "Volume of square "
<< " base pyramid is "
<< volumeSquare(b, h)
<< endl;
cout << "Volume of pentagonal"
<< " base pyramid is "
<< volumePentagonal(a, b, h)
<< endl;
929
Chapter 169. Program for volume of Pyramid
cout << "Volume of Hexagonal"
<< " base pyramid is "
<< volumeHexagonal(a, b, h);
return 0;
}
Java
930
Chapter 169. Program for volume of Pyramid
Python3
931
Chapter 169. Program for volume of Pyramid
C#
932
Chapter 169. Program for volume of Pyramid
return vol;
}
// Function to find the volume
// of pentagonal pyramid
public static float volumePentagonal(int a,
int b,
int h)
{
float vol = (float)(0.83) * a * b * h;
return vol;
}
// Function to find the volume
// of hexagonal pyramid
public static float volumeHexagonal(int a,
int b,
int h)
{
float vol = (float)a * b * h;
return vol;
}
// Driver Code
public static void Main()
{
int b = 4, h = 9, a = 4;
Console.WriteLine("Volume of triangular"+
" base pyramid is " +
volumeTriangular(a, b, h));
Console.WriteLine("Volume of square "+
"base pyramid is " +
volumeSquare(b, h));
Console.WriteLine("Volume of pentagonal"+
" base pyramid is " +
volumePentagonal(a, b, h));
Console.WriteLine("Volume of Hexagonal"+
" base pyramid is " +
volumeHexagonal(a, b, h));
}
}
// This code is contributed by vt_m
PHP
933
Chapter 169. Program for volume of Pyramid
<?php
// PHP program to find the volume.
// Function to find the volume
// of triangular pyramid
function volumeTriangular($a, $b, $h)
{
$vol = (0.1666) * $a * $b * $h;
return $vol;
}
// Function to find the
// volume of square pyramid
function volumeSquare($b, $h)
{
$vol = (0.33) * $b * $b * $h;
return $vol;
}
// Function to find the volume
// of pentagonal pyramid
function volumePentagonal($a, $b, $h)
{
$vol = (0.83) * $a * $b * $h;
return $vol;
}
// Function to find the volume
// of hexagonal pyramid
function volumeHexagonal($a, $b, $h)
{
$vol = $a * $b * $h;
return $vol;
}
// Driver Code
$b = 4; $h = 9; $a = 4;
echo ("Volume of triangular base pyramid is ");
echo( volumeTriangular($a, $b, $h));
echo("\n");
echo ("Volume of square base pyramid is ");
echo( volumeSquare($b, $h));
echo("\n");
echo ("Volume of pentagonal base pyramid is ");
echo(volumePentagonal($a, $b, $h));
echo("\n");
echo("Volume of Hexagonal base pyramid is ");
echo(volumeHexagonal($a, $b, $h));
934
Chapter 169. Program for volume of Pyramid
// This code is contributed by vt_m
?>
Output :
Improved By : vt_m
Source
https://www.geeksforgeeks.org/program-for-volume-of-pyramid/
935
Chapter 170
Formula :
Examples :
936
Chapter 170. Program to calculate Area Of Octagon
Input : side = 3
Output : Area of Regular Octagon = 43.4558
Input : side = 4
Output : Area of Regular Octagon = 77.2548
C++
Java
937
Chapter 170. Program to calculate Area Of Octagon
double side = 4;
System.out.print("Area of Regular Octagon = "
+ areaOctagon(side));
}
}
// This code is contributed by Anant Agarwal.
Python3
C#
// C# Program to find
// area of Octagon.
using System;
class GFG
{
// utility function
static double areaOctagon(double side)
{
return (float)(2 * (1 + Math.Sqrt(2))
* side * side);
}
// Driver code
public static void Main()
{
double side = 4;
Console.WriteLine("Area of Regular Octagon = "
938
Chapter 170. Program to calculate Area Of Octagon
+ areaOctagon(side));
}
}
// This code is contributed by vt_m.
PHP
<?php
// PHP program to find area of octagon
// Utility function
function areaOctagon( $side)
{
return (2 * (1 + sqrt(2)) *
$side * $side);
}
// Driver Code
$side = 4;
echo("Area of Regular Octagon = ");
echo(areaOctagon($side));
// This code is contributed by vt_m.
?>
Output :
Improved By : vt_m
Source
https://www.geeksforgeeks.org/program-calculate-area-octagon/
939
Chapter 171
surface area =
volume =
Examples :
Input : Radius = 7
Output : Volume = 718.378
940
Chapter 171. Program to calculate Volume and Surface area of Hemisphere
Input : Radius = 11
Output : Volume = 2787.64
Surface Area = 760.265
C++
Java
941
Chapter 171. Program to calculate Volume and Surface area of Hemisphere
Python
C#
942
Chapter 171. Program to calculate Volume and Surface area of Hemisphere
PHP
<?php
// PHP Program to calulate volume and
// and surface area of a Hemisphere.
// Initializing value of pi &
// Function to calulate volume
function volume($r)
{
$pi =3.141592653589793;
$volume = (2 * $pi *
943
Chapter 171. Program to calculate Volume and Surface area of Hemisphere
Output :
Volume = 2787.64
Surface Area = 760.265
Improved By : vt_m
Source
https://www.geeksforgeeks.org/program-calculate-volume-surface-area-hemisphere/
944
Chapter 172
Formula :
Examples :
945
Chapter 172. Program to calculate area and perimeter of Trapezium
Input : a = 5, b = 6, c = 4, d = 3, h = 8
Output : Area of Trapezium : 44
Perimeter of Trapezium : 18
C++
Java
946
Chapter 172. Program to calculate area and perimeter of Trapezium
Python3
947
Chapter 172. Program to calculate area and perimeter of Trapezium
# Function to calculate
# Area of trapezium
def areaTrapezium (a, b, h):
return (1.0 / 2 * (a + b) * h)
# Function to calculate
# perimeter of trapezium
def perimeterTrapezium (a, b, c, d):
return (a + b + c + d)
# Driver function
a = 5
b = 15
c = 11
d = 4
h = 20
print("Area of Trapezium =",
areaTrapezium(a, b, h))
print("Perimeter of Trapezium =",
perimeterTrapezium(a, b, c, d))
# This code is contributed by "Sharad_Bhardwaj"
C#
948
Chapter 172. Program to calculate area and perimeter of Trapezium
PHP
<?php
// PHP program to find area
// and perimeter of trapezium
// Function to calculate
// Area of trapezium
function areaTrapezium($a, $b, $h)
{
return (1.0 / 2 * ($a + $b) * $h);
}
// Function to calculate
// perimeter of trapezium
function perimeterTrapezium($a, $b,
$c, $d)
{
return ($a + $b + $c + $d);
}
// Driver Code
949
Chapter 172. Program to calculate area and perimeter of Trapezium
$a = 5; $b = 15;$c = 11;
$d = 4; $h = 20;
echo ("Area of Trapezium = ");
echo(areaTrapezium($a, $b, $h));
echo("\n");
echo( "Perimeter of Trapezium = ");
echo(perimeterTrapezium($a, $b, $c, $d));
// This code is contributed by vt_m.
?>
Output:
Improved By : vt_m
Source
https://www.geeksforgeeks.org/program-calculate-area-perimeter-trapezium/
950
Chapter 173
• If we know the length of each sides of equilateral triangle, then we can use below
mentioned formula to calculate area of equilateral triangle.
• If we know the length of altitude of equilateral triangle along with the length of side,
then we can use below mentioned formula to calculate it’s area.
951
Chapter 173. Program to calculate area and perimeter of equilateral triangle
Examples :
Input : side = 4
Output : Area of Equilateral Triangle: 6.9282
Perimeter of Equilateral Triangle: 12
Input : side = 12
Output : Area of Equilateral Triangle: 62.3538
Perimeter of Equilateral Triangle: 36
C++
952
Chapter 173. Program to calculate area and perimeter of equilateral triangle
int main()
{
float side = 4;
cout << "Area of Equilateral Triangle: "
<< area_equi_triangle(side) << endl;
cout << "Perimeter of Equilateral Triangle: "
<< peri_equi_triangle(side);
return 0;
}
Java
953
Chapter 173. Program to calculate area and perimeter of equilateral triangle
Python
C#
954
Chapter 173. Program to calculate area and perimeter of equilateral triangle
return 3 * side;
}
// Driver Code
public static void Main()
{
float side = 4;
Console.Write("Area of Equilateral Triangle:");
Console.WriteLine(area_equi_triangle(side));
Console.Write("Perimeter of Equilateral Triangle:");
Console.WriteLine(peri_equi_triangle(side));
}
}
// This code is contributed
// by vt_m.
PHP
<?php
// PHP program to find area
// and perimeter of equilateral triangle
// Function to calculate Area
// of equilateral triangle
function area_equi_triangle( $side)
{
return sqrt(3) / 4 * $side * $side;
}
// Function to calculate Perimeter
// of equilateral triangle
function peri_equi_triangle( $side)
{
return 3 * $side;
}
// Driver Code
$side = 4;
echo("Area of Equilateral Triangle: ");
echo(area_equi_triangle($side));
echo("\n");
echo("Perimeter of Equilateral Triangle: ");
echo( peri_equi_triangle($side));
// This code is contributed
955
Chapter 173. Program to calculate area and perimeter of equilateral triangle
// by vt_m.
?>
Output :
Improved By : vt_m
Source
https://www.geeksforgeeks.org/program-calculate-area-perimeter-equilateral-triangle/
956
Chapter 174
957
Chapter 174. Program to calculate area and volume of a Tetrahedron
Area = sqrt(3)*(side*side)
Examples :
Input : side = 3
Output : 15.5885
Input : side = 20
Output : 692.82
Java
958
Chapter 174. Program to calculate area and volume of a Tetrahedron
{
return (Math.sqrt(3) * (side * side));
}
// Driver code
public static void main(String[] args)
{
int side = 3;
System.out.println("Area of Tetrahedron ="
+ area_of_tetrahedron(side));
}
}
// This code is contributed
// by Prasad Kshirsagar
Python3
C#
// C# Program to Calculate
// area of tetrahedron
using System;
class GFG
{
// Utility Function
public static double area_of_tetrahedron(int side)
{
return (Math.Sqrt(3) *
(side * side));
959
Chapter 174. Program to calculate area and volume of a Tetrahedron
}
// Driver code
static public void Main ()
{
int side = 3;
Console.WriteLine("Area of Tetrahedron = " +
area_of_tetrahedron(side));
}
}
// This code is contributed
// by akt_mit
PHP
<?php
// PHP Program to Calculate
// area of tetrahedron
function area_of_tetrahedron($side)
{
return (sqrt(3) * ($side * $side));
}
// Driver Code
$side = 3;
echo "Area of Tetrahedron = ",
area_of_tetrahedron($side);
// This code is contributed by aj_36.
?>
Output :
The volume of the tetrahedron can be found by using the following formula :
Volume = a3 /(6√2)
Examples :
960
Chapter 174. Program to calculate area and volume of a Tetrahedron
Input : side = 3
Output : 3.18
Input : side = 20
Output : 942.81
C/C++
Java
961
Chapter 174. Program to calculate area and volume of a Tetrahedron
Python
C#
PHP
<?php
962
Chapter 174. Program to calculate area and volume of a Tetrahedron
Output :
3.18
Source
https://www.geeksforgeeks.org/calculate-area-tetrahedron/
963
Chapter 175
Input : side = 6
Output : Area of circumscribed circle is: 37.69
Input : side = 9
Output : Area of circumscribed circle is: 84.82
All three sides of equilateral triangle are of equal length and all three interior angles are 60
degrees.
Properties of a Circumcircle are as follows:
• The center of the circumcircle is the point where the medians of the equilateral triangle
intersect.
• Circumscribed circle of an equilateral triangle is made through the three vertices of
an equilateral triangle.
• The radius of a circumcircle of an equilateral triangle is equal to (a / √3), where ‘a’ is
the length of the side of equilateral triangle.
964
Chapter 175. Program to calculate area of Circumcircle of an Equilateral Triangle
(�*a2)/3
965
Chapter 175. Program to calculate area of Circumcircle of an Equilateral Triangle
{
float a = 6;
printf("Area of circumscribed circle is :%f",
area_circumscribed(a));
return 0;
}
Java
Python3
966
Chapter 175. Program to calculate area of Circumcircle of an Equilateral Triangle
%area_cicumscribed(a))
# This code is contributed by Anant Agarwal.
C#
PHP
<?php
// PHP program to find the
// area of Cicumscribed
// circle of equilateral triangle
$PI = 3.14159265;
// function to find area of
// circumscribed circle
function area_circumscribed($a)
{
global $PI;
return ($a * $a * ($PI / 3));
}
967
Chapter 175. Program to calculate area of Circumcircle of an Equilateral Triangle
// Driver code
$a = 6;
echo("Area of circumscribed circle is :");
echo(area_circumscribed($a));
// This code is contributed by Ajit.
?>
Source
https://www.geeksforgeeks.org/program-calculate-area-circumcircle-equilateral-triangle/
968
Chapter 176
969
Chapter 176. Program to calculate area of Enneagon
Examples:
Input : 6
Output :Area of Regular Nonagon = 222.5448
Input : 8
Output :Area of Regular Nonagon = 395.6352
C++
Java
970
Chapter 176. Program to calculate area of Enneagon
Python
C#
PHP
<?php
// PHP program to find area of a Hexagon
// Function to calculate
// area of nonagon
function Nonagon_Area($s)
{
971
Chapter 176. Program to calculate area of Enneagon
Output:
Improved By : vt_m
Source
https://www.geeksforgeeks.org/program-to-calculate-area-of-enneagon/
972
Chapter 177
where “b” is the length of the base, “h” is the height of the triangle, “s1, s2, s3” are the
respective length of each side of the triangle, and H is the height of the prism (which is also
the length of the rectangle).
Given the base, the height of the triangle, height of prism and the length of each side of
triangle base and the task is to calculate the surface area of the triangular prism.
Examples:
Input: b = 3, h = 4, s1 = 3, s2 = 6, s3 = 6, Ht = 8
Output: The area of triangular prism is 132.000000
973
Chapter 177. Program to calculate the Surface Area of a Triangular Prism
Input: b = 2, h = 3, s1 = 4, s2 = 5, s3 = 6, Ht = 8
Output: The area of triangular prism is 126.000000
SA = b * h + (s1 + s2 + s3 ) * H
C++
974
Chapter 177. Program to calculate the Surface Area of a Triangular Prism
C#
975
Chapter 177. Program to calculate the Surface Area of a Triangular Prism
Java
PHP
<?php
// PHP Program to calculate
// the Surface area of a
// triangular prism
// Function for calculating
// the area
function Calculate_area()
{
// Initialization
$b = 3; $h = 4;
$s1 = 3; $s2 = 6;
$s3 = 6; $Ht = 8; $SA;
// Formula for calculating
// the area
$SA = $b * $h + ($s1 +
$s2 + $s3) * $Ht;
976
Chapter 177. Program to calculate the Surface Area of a Triangular Prism
// Displaying the area
echo "The area of triangular".
" prism is : " , $SA;
}
// Driver code
// Function calling
Calculate_area();
// This code is contributed by m_kit
?>
Output:
Source
https://www.geeksforgeeks.org/program-to-calculate-the-surface-area-of-a-triangular-prism/
977
Chapter 178
978
Chapter 178. Program to calculate volume of Ellipsoid
float r3)
{
float pi = 3.14;
return 1.33 * pi * r1 *
r2 * r3;
}
// Driver Code
int main()
{
float r1 = 2.3, r2 = 3.4, r3 = 5.7;
cout << "volume of ellipsoid is : "
<< volumeOfEllipsoid(r1, r2, r3);
return 0;
}
Java
979
Chapter 178. Program to calculate volume of Ellipsoid
Python
''' Python3 program to Volume of ellipsoid'''
import math
# Function To calculate Volume
def volumeOfEllipsoid(r1, r2, r3):
return 1.33 * math.pi * r1 * r2 * r3
# Driver Code
r1 = float(2.3)
r2 = float(3.4)
r3 = float(5.7)
print( "Volume of ellipsoid is : ",
volumeOfEllipsoid(r1, r2, r3) )
C#
980
Chapter 178. Program to calculate volume of Ellipsoid
PHP
<?php
// PHP program to find the
// volume of Ellipsoid.
// Function to find the volume
function volumeOfEllipsoid( $r1,
$r2,
$r3)
{
$pi = 3.14;
return 1.33 * $pi * $r1 *
$r2 * $r3;
}
// Driver Code
$r1 = 2.3; $r2 = 3.4;
$r3 = 5.7;
echo ( "volume of ellipsoid is : ");
echo( volumeOfEllipsoid($r1, $r2, $r3));
// This code is contributed by vt_m .
?>
Output :
Improved By : vt_m
Source
https://www.geeksforgeeks.org/program-calculate-volume-ellipsoid/
981
Chapter 179
Input : 3
Output : 12.7279
Input : 7
Output : 161.692
A regular Octahedron has eight faces,twelve edges and six vertices. It has eight triangles
with edges of equal length and effectively two square pyramids meeting at their bases.
982
Chapter 179. Program to calculate volume of Octahedron
Properties of Octahedron:
Number of faces: 8
Number of edges: 12
Number of vertices: 6
Volume = √2/3 × a3 where a is the side of Octahedron
CPP
983
Chapter 179. Program to calculate volume of Octahedron
Java
Python3
C#
984
Chapter 179. Program to calculate volume of Octahedron
// C# Program to calculate
// volume of Octahedron
using System;
class GFG
{
public static void Main ()
{
// Driver Function
double side = 3;
Console.Write("Volume of octahedron = ");
Console.WriteLine(vol_of_octahedron(side));
}
// utility Function
static double vol_of_octahedron(double side)
{
return ((side*side*side)*(Math.Sqrt(2)/3));
}
}
// This code is contributed
// by vt_m.
PHP
<?php
// PHP Program to calculate
// volume of Octahedron
// utility Function
function vol_of_octahedron( $side)
{
return (($side * $side *
$side) * (sqrt(2) / 3));
}
// Driver Function
$side = 3;
echo ("Volume of octahedron =");
echo(vol_of_octahedron($side));
// This code is contributed
// by vt_m.
?>
Output:
985
Chapter 179. Program to calculate volume of Octahedron
Improved By : vt_m
Source
https://www.geeksforgeeks.org/program-calculate-volume-octahedron/
986
Chapter 180
Congruent triangles are two or more triangles that have all corresponding sides that are
equal or a pair of sides and between angle are equal or a pair of angle and side between are
equal or a pair of angle and other side are equal or hypotenuse and one side are equal.
987
Chapter 180. Program to check congruency of two triangles
1. Side-Side-Side (SSS) Congruency criteria: If all the sides of a triangle are equal
988
Chapter 180. Program to check congruency of two triangles
to the sides of another triangle then the triangles are said to be congruent by the
property of Side-Side-Side (SSS).
In above triangle ABC and A’B’C’ if, AB=A’B’ and BC=B’C’ and CA=C’A’ then,
triangles are congruent.
2. Side-Angle-Side (SAS) Congruent criteria: If two sides of the two triangles are
equal and the angle between them is same in both triangle then the triangles are said
to be congruent by the property of Side-Angle-Side (SAS). In above triangle ABC and
989
Chapter 180. Program to check congruency of two triangles
990
Chapter 180. Program to check congruency of two triangles
# Function for AAS congruency
def cong_aas(s1, s2, a1, a2):
s1 = [float(i) for i in s1]
s2 = [float(i) for i in s2]
a1 = [float(i) for i in a1]
a2 = [float(i) for i in a2]
s1.sort()
s2.sort()
a1.sort()
a2.sort()
# Check for AAS
# side other two smallest angle is smallest or 2nd smallest.
if a1[0] == a2[0] and a1[1] == a2[1]:
# since we take side other than angles.
if s1[0] == s2[0] or s1[1] == s2[1]:
return 1
if a1[1] == a2[1] and a1[2] == a2[2]:
if s1[1] == s2[1] or s1[2] == s2[2]:
return 1
if a1[2] == a2[2] and a1[0] == a2[0]:
if s1[0] == s2[0] or s1[2] == s2[2]:
return 1
return 0
# Function for HL congruency
def cong_hl(s1, s2):
s1 = [float(i) for i in s1]
s2 = [float(i) for i in s2]
s1.sort()
s2.sort()
# Check for HL
if s1[2] == s2[2]:
if s1[1] == s2[1] or s1[0] == s2[0]:
return 1
return 0
991
Chapter 180. Program to check congruency of two triangles
Output:
992
Chapter 180. Program to check congruency of two triangles
Source
https://www.geeksforgeeks.org/program-to-check-congruency-of-two-triangles/
993
Chapter 181
Program to check if tank will overflow, underflow or filled in given time - GeeksforGeeks
Given a tank with definite height and radius and the flow of water available to fill the tank.
Determine whether the tank will overflow or not in a given amount of time.
Note: The flow of water will be available in volume per minute.
Examples:
--r=5--
---------- ^
| | |
| | |
| | h = 10
| | |
---------- ^
rate_of_flow = 10
Approach:
Volume of a cylindrical tank is (22/7) * radius * radius * height. First, find out the amount
994
Chapter 181. Program to check if tank will overflow, underflow or filled in given time
of time required to completely fill the tank then compare it with the given time. If the given
time is greater than required time, it will result in an overflow condition. If the given time is
less than the required time then it will result in an underflow condition otherwise the tank
is filled.
Below is the implementation of above approach:
C++
995
Chapter 181. Program to check if tank will overflow, underflow or filled in given time
return 0;
}
Java
996
Chapter 181. Program to check if tank will overflow, underflow or filled in given time
Python3
C#
997
Chapter 181. Program to check if tank will overflow, underflow or filled in given time
}
// function to print overflow / filled /
// underflow accordingly
public static void check_and_print(double required_time,
double given_time)
{
if (required_time < given_time)
Console.WriteLine("Overflow");
else if (required_time > given_time)
Console.WriteLine("Underflow");
else
Console.WriteLine("Filled");
}
// driver code
public static void Main()
{
int radius = 5, // radius of the tank
height = 10, // height of the tank
rate_of_flow = 10; // rate of flow of water
double given_time = 70.0; // time given
// calculate the required time
double required_time = volume(radius, height) / rate_of_flow;
// printing the result
check_and_print(required_time, given_time);
}
}
// This code is contributed by vt_m
PHP
<?php
// PHP program to check if Tank will
// overflow or not in given time
// function to calculate
// the volume of tank
function volume($radius, $height)
{
return ((22 / 7) * $radius *
$radius * $height);
}
998
Chapter 181. Program to check if tank will overflow, underflow or filled in given time
Output:
Underflow
Improved By : jit_t
Source
https://www.geeksforgeeks.org/program-check-tank-will-overflow-underflow-filled-given-time/
999
Chapter 182
To find the points parallel to X or Y axis just check if the points are same for
any axis or not. If all the points on X axis are same then the line is parallel
to X axis. If all the points on Y axis are same so the line is parallel to Y axis
otherwise it is not parallel to any axis.
Input the value N. And then Input the value of points in a
1000
Chapter 182. Program to check if the points are parallel to X axis or Y axis
C++
1001
Chapter 182. Program to check if the points are parallel to X axis or Y axis
Java
1002
Chapter 182. Program to check if the points are parallel to X axis or Y axis
PHP
<?php
// PHP program to check for parallel
// to X and Y Axis
// To check for parallel line
function parallel($n, $a)
{
$x = true; $y = true;
// checking for parallel
// to X and Y axis condition
for ($i = 0; $i < $n - 1; $i++)
{
for ($j = 0; $j < 2; $j++)
{
if ($a[$i][0] != $a[$i + 1][0])
$x = false;
if ($a[$i][1] != $a[$i + 1][1])
$y = false;
}
}
// To display the output
if ($x)
echo "parallel to X Axis" ;
else if (y)
1003
Chapter 182. Program to check if the points are parallel to X axis or Y axis
Output:
Parallel to X Axis
Improved By : vt_m
Source
https://www.geeksforgeeks.org/program-check-points-parallel-x-axis-y-axis/
1004
Chapter 183
First approach
Three points lie on the straight line if the area formed by the triangle of these three points
is zero. So we will check if the area formed by the triangle is zero or not
1005
Chapter 183. Program to check if three points are collinear
Java
1006
Chapter 183. Program to check if three points are collinear
Python
1007
Chapter 183. Program to check if three points are collinear
if (a == 0):
print "Yes"
else:
print "No"
# Driver Code
x1, x2, x3, y1, y2, y3 = 1, 1, 1, 1, 4, 5
collinear(x1, y1, x2, y2, x3, y3)
# This code is contributed
# by Sachin Bisht
C#
1008
Chapter 183. Program to check if three points are collinear
collinear(x1, y1, x2, y2, x3, y3);
}
}
// This code is contributed by Sam007.
PHP
<?php
// PHP or not using area of triangle.
/* function to check if
point collinear or not */
function collinear($x1, $y1, $x2,
$y2, $x3, $y3)
{
/* Calculation the area of
triangle. We have skipped
multiplication with 0.5 to
avoid floating point computations */
$a = $x1 * ($y2 - $y3) +
$x2 * ($y3 - $y1) +
$x3 * ($y1 - $y2);
if ($a == 0)
printf("Yes");
else
printf("No");
}
// Driver Code
$x1 = 1; $x2 = 1; $x3 = 1;
$y1 = 1; $y2 = 4; $y3 = 5;
collinear($x1, $y1, $x2, $y2, $x3, $y3);
// This code is contributed by Sam007.
?>
Output :
Yes
Second approach
1009
Chapter 183. Program to check if three points are collinear
In other words,
(y3 - y2)(x2 - x1) = (y2 - y1)(x3 - x2)
Python
1010
Chapter 183. Program to check if three points are collinear
# function to check if
# point collinear or not
def collinear(x1, y1, x2, y2, x3, y3):
if ((y3 - y2)*(x2 - x1) == (y2 - y1)*(x3 - x2)):
print ("Yes")
else:
print ("No")
# Driver Code
x1, x2, x3, y1, y2, y3 = 1, 1, 0, 1, 6, 9
collinear(x1, y1, x2, y2, x3, y3);
# This code is contributed
# by Sachin Bisht
Output :
No
Improved By : Sam007
Source
https://www.geeksforgeeks.org/program-check-three-points-collinear/
1011
Chapter 184
Program to check if water tank overflows when n solid balls are dipped in the water tank -
GeeksforGeeks
Given the dimensions of cylindrical water tank, spherical solid balls and the amount of water
present in the tank check if water tank will overflow when balls are dipped in the water tank.
Examples :
input : H = 10, r = 5
h = 5
N = 2, R = 2
output : Not in overflow state
Explanation :
water tank capacity = 3.14 * r * r * H
= 3.14 * 5 * 5 * 10
= 785
1012
Chapter 184. Program to check if water tank overflows when n solid balls are dipped in the
water tank
input : H = 5, r = 3
h = 3
N = 3, R = 2
output : Overflow
Explanation:
water tank capacity = 3.14 * r * r * H
= 3.14 * 3 * 3 * 5
= 141.3
Approach:
When solid balls are dipped in water, level of water increases, hence volume of water will
also increase.
Increasing in water volume = Total volume of dip balls
Volume of Cylinder = 3.14 * r * r * h
where: r: radius of tank
h: height of tank
Number of balls are n
Balls have shape of Sphere
Volume of Sphere = (4/3) * 3.14 * R * R * R
Where R: Sphere’s(solid ball) radius
After dipping all balls, if the total volume of water and all balls is less than or equal to the
total volume of tank capacity then there will no overflow in tank, otherwise there will be
overflow.
Below is the implementation of above approach:
C++
1013
Chapter 184. Program to check if water tank overflows when n solid balls are dipped in the
water tank
Java
1014
Chapter 184. Program to check if water tank overflows when n solid balls are dipped in the
water tank
1015
Chapter 184. Program to check if water tank overflows when n solid balls are dipped in the
water tank
Python3
C#
1016
Chapter 184. Program to check if water tank overflows when n solid balls are dipped in the
water tank
PHP
1017
Chapter 184. Program to check if water tank overflows when n solid balls are dipped in the
water tank
<?php
// PHP Program to check if water tank
// overflows when n solid balls are
// dipped in the water tank
// function to find if tank
// will overflow or not
function overflow($H, $r, $h,
$N, $R)
{
// cylinder capacity
$tank_cap = 3.14 * $r *
$r * $H;
// volume of water in tank
$water_vol = 3.14 * $r *
$r * $h;
// volume of n balls
$balls_vol = $N * (4/3) *
3.14 * $R *
$R * $R;
// total volume of water
// and n dipped balls
$vol = $water_vol + $balls_vol;
// condition to check if tank
// is in overflow state or not
if($vol > $tank_cap)
{
echo "Overflow", "\n";
}
else
{
echo "Not in overflow state", "\n";
}
}
// Driver Code
// giving dimensions
$H = 10; $r = 5; $h = 5;
$N = 2; $R = 2;
// calling function
overflow ($H, $r, $h, $N, $R);
1018
Chapter 184. Program to check if water tank overflows when n solid balls are dipped in the
water tank
// This code is contributed by aj_36
?>
Output :
Improved By : jit_t
Source
https://www.geeksforgeeks.org/program-check-water-tank-overflows-n-solid-balls-dipped-water-tank/
1019
Chapter 185
Similar triangles are two or more triangles that have all corresponding angles that are equal
and all corresponding sides that are proportionate. It does not matter what direction the
triangles are facing. Their size does not matter as long as each side is proportionate. The
similarity of triangles can be proved by the following theorems:
1020
Chapter 185. Program to check similarity of given two triangles
1021
Chapter 185. Program to check similarity of given two triangles
1022
Chapter 185. Program to check similarity of given two triangles
1023
Chapter 185. Program to check similarity of given two triangles
1024
Chapter 185. Program to check similarity of given two triangles
1025
Chapter 185. Program to check similarity of given two triangles
C++
1026
Chapter 185. Program to check similarity of given two triangles
1027
Chapter 185. Program to check similarity of given two triangles
Java
1028
Chapter 185. Program to check similarity of given two triangles
return 0;
}
// Function for
// SAS similarity
static int simi_sas(int s1[], int s2[],
int a1[], int a2[])
{
Arrays.sort(a1);
Arrays.sort(a2);
Arrays.sort(s1);
Arrays.sort(s2);
// Check for SAS
// angle b / w two smallest
// sides is largest.
if(s1[0] / s2[0] == s1[1] / s2[1])
{
// since we take angle
// b / w the sides.
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;
}
// Function for
// SSS similarity
static int simi_sss(int s1[],
int s2[])
{
Arrays.sort(s1);
Arrays.sort(s2);
// Check for SSS
if(s1[0] / s2[0] == s1[1] / s2[1] &&
1029
Chapter 185. Program to check similarity of given two triangles
1030
Chapter 185. Program to check similarity of given two triangles
Python
1031
Chapter 185. Program to check similarity of given two triangles
# Function for SSS similarity
def simi_sss(s1, s2):
s1 = [float(i) for i in s1]
s2 = [float(i) for i in s2]
s1.sort()
s2.sort()
# Check for SSS
if(s1[0] / s2[0] == s1[1] / s2[1]
and s1[1] / s2[1] == s1[2] / s2[2]
and s1[2] / s2[2] == s1[0] / s2[0]):
return 1
return 0
# Driver Code
s1 = [2, 3, 3]
s2 = [4, 6, 6]
a1 = [80, 60, 40]
a2 = [40, 60, 80]
# function call for AAA similarity
aaa = simi_aaa(a1, a2)
# function call for SSS similarity
sss = simi_sss(s1, s2)
# function call for SAS similarity
sas = simi_sas(s1, s2, a1, a2)
# Check if triangles are similar or not
if aaa or sss or sas:
print "Triangles are similar by",
if aaa: print "AAA",
if sss: print "SSS",
if sas: print "SAS"
else: print "Triangles are not similar"
Output:
1032
Chapter 185. Program to check similarity of given two triangles
Improved By : andrew1234
Source
https://www.geeksforgeeks.org/program-to-check-similarity-of-given-two-triangles/
1033
Chapter 186
1034
Chapter 186. Program to check whether 4 points in a 3-D plane are Coplanar
Examples:
Input:
x1 = 3, y1 = 2, z1 = -5
x2 = -1, y2 = 4, z2 = -3
x3 = -3, y3 = 8, z3 = -5
x4 = -3, y4 = 2, z4 = 1
Output: Coplanar
Input:
x1 = 0, y1 = -1, z1 = -1
x2 = 4, y2 = 5, z2 = 1
x3 = 3, y3 = 9, z3 = 4
x4 = -4, y4 = 4, z4 = 3
Output: Not Coplanar
1035
Chapter 186. Program to check whether 4 points in a 3-D plane are Coplanar
Approach:
1. To check whether 4 points are coplanar or not, first of all, find the equation of the
plane passing through any three of the given points.
Approach to find equation of a plane passing through 3 points.
2. Then, check whether the 4th point satisfies the equation obtained in step 1. That is,
putting the value of 4th point in the equation obtained. If it satisfies the equation
then the 4 points are Coplanar otherwise not.
1036
Chapter 186. Program to check whether 4 points in a 3-D plane are Coplanar
y3 = 8
z3 = -5
x4 = -3
y4 = 2
z4 = 1
equation_plane(x1, y1, z1, x2, y2, z2, x3,
y3, z3, x4, y4, z4)
Output:
Coplanar
Source
https://www.geeksforgeeks.org/program-to-check-whether-4-points-in-a-3-d-plane-are-coplanar/
1037
Chapter 187
Input: 2, 3, 4
Output: Point lies in 1st octant
Input: -4, 2, -8
Output: Point lies in 6th octant
Input: -6, -2, 8
Output: Point lies in 3rd octant
Approach: Given below are the conditions which need to be checked in order to determine
the octant of the axial plane.
• Check if x >= 0 and y >= 0 and z >= 0, then Point lies in 1st octant.
• Check x < 0 and y >= 0 and z >= 0, then Point lies in 2nd octant.
• Check if x < 0 and y < 0 and z >= 0, then Point lies in 3rd octant.
• Check if x >= 0 and y < 0 and z >= 0, then Point lies in 4th octant.
• Check if x >= 0 and y >= 0 and z < 0, then Point lies in 5th octant.
• Check if x < 0 and y >= 0 and z < 0, then Point lies in 6th octant.
• Check if x < 0 and y < 0 and z < 0, then Point lies in 7th octant.
• Check if x >= 0 and y < 0 and z < 0, then Point lies in 8th octant.
1038
Chapter 187. Program to determine the octant of the axial plane
1039
Chapter 187. Program to determine the octant of the axial plane
Python
PHP
<?php
// PHP program to print octant
1040
Chapter 187. Program to determine the octant of the axial plane
// of a given point.
// Function to print octant
function octant($x, $y, $z)
{
if ($x >= 0 && $y >= 0 && $z >= 0)
echo "Point lies in 1st octant\n";
else if ($x < 0 && $y >= 0 && $z >= 0)
echo "Point lies in 2nd octant\n";
else if ($x < 0 && $y < 0 && $z >= 0)
echo "Point lies in 3rd octant\n";
else if ($x >= 0 && $y < 0 && $z >= 0)
echo "Point lies in 4th octant\n";
else if ($x >= 0 && $y >= 0 && $z < 0)
echo "Point lies in 5th octant\n";
else if ($x < 0 && $y >= 0 && $z < 0)
echo "Point lies in 6th octant\n";
else if ($x < 0 && $y < 0 && $z < 0)
echo "Point lies in 7th octant\n";
else if ($x >= 0 && $y < 0 && $z < 0)
echo "Point lies in 8th octant\n";
}
// Driver Code
$x = 2;
$y = 3;
$z = 4;
octant($x, $y, $z) ;
$x = -4;
$y = 2;
$z = -8;
octant($x, $y, $z);
$x = -6;
$y = -2;
$z = 8;
octant($x, $y, $z);
// This code is contributed
// by Amber_Saxena.
1041
Chapter 187. Program to determine the octant of the axial plane
?>
Output:
Improved By : Amber_Saxena
Source
https://www.geeksforgeeks.org/program-to-determine-the-octant-of-the-axial-plane/
1042
Chapter 188
Input : a = 5, b = 8, c = 49
Output : 6.04339
In particular, the Law of Cosines can be used to find the length of the third side of a triangle
when you know the length of two sides and the angle in between. See here to learn to how
to find the value of cos.
Let us assume a, b, c are the sides of triangle where c is the side across from angle C. Then,
1043
Chapter 188. Program to find third side of triangle using law of cosines
C++
1044
Chapter 188. Program to find third side of triangle using law of cosines
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;
}
// Function to find third side
float third_side(int a, int b, float c)
{
float angle = cal_cos(c);
return sqrt((a * a) + (b * b) - 2 * a * b * angle);
}
// Driver program to check the above function
int main()
{
float c = 49;
int a = 5, b = 8;
// function call
cout << third_side(a, b, c);
return 0;
}
Java
1045
Chapter 188. Program to find third side of triangle using law of cosines
C#
1046
Chapter 188. Program to find third side of triangle using law of cosines
class GFG
{
// Function to calculate
// cos value of angle c
static float cal_cos(float n)
{
float accuracy = 0.0001f, x1;
float denominator, cosx, cosval;
// Converting degrees to radian
n = n * (3.142f / 180.0f);
x1 = 1;
// Maps the sum along the series
cosx = x1;
// Holds the actual value of sin(n)
cosval = (float)Math.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 <=
Math.Abs(cosval - cosx));
return cosx;
}
// Function to find third side
static float third_side(int a,
int b, float c)
{
float angle = cal_cos(c);
return (float)Math.Sqrt((a * a) +
(b * b) - 2 * a * b * angle);
}
// Driver code
public static void Main ()
{
float c = 49;
int a = 5, b = 8;
// function call
1047
Chapter 188. Program to find third side of triangle using law of cosines
Console.WriteLine(Math.Round(third_side(a,
b, c)*100000.0)/100000.0);
}
}
// This code is contributed by vt_m.
PHP
<?php
// PHP program to find third
// side of triangle using
// law of cosines
// Function to calculate
// cos value of angle c
function cal_cos( $n )
{
$accuracy = 0.0001;
$x1; $denominator;
$cosx; $cosval;
// Converting degrees
// to radian
$n = $n * (3.142 / 180.0);
$x1 = 1;
// Maps the sum
// along the series
$cosx = $x1;
// Holds the actual
// value of sin(n)
$cosval = cos($n);
$i = 1;
do
{
$denominator = 2 * $i *
(2 * $i - 1);
$x1 = -$x1 * $n * $n /
$denominator;
$cosx = $cosx + $x1;
$i = $i + 1;
} while ($accuracy <= ($cosval -
$cosx));
return $cosx;
1048
Chapter 188. Program to find third side of triangle using law of cosines
}
// Function to find third side
function third_side($a, $b, $c)
{
$angle = cal_cos($c);
return sqrt(($a * $a) +
($b * $b) - 2 *
$a * $b * $angle);
}
// Driver Code
$c = 49;
$a = 5;
$b = 8;
// function call
echo third_side($a, $b, $c);
// This code is contributed
// by ajit
?>
Output:
6.04339
Improved By : jit_t
Source
https://www.geeksforgeeks.org/program-find-third-side-triangle-using-law-cosines/
1049
Chapter 189
Input : P(6, 0)
Q(0, 0)
R(0, 8)
Output : The circumcenter of the triangle PQR
is: (3, 4)
Input : P(1, 1)
Q(0, 0)
R(2, 2)
Output : The two perpendicular bisectors found
come parallel. Thus, the given points
do not form a triangle and are collinear
Given, three points of the triangle, we can easily find the sides of the triangle. Now, we
have the equations of the lines for the three sides of the triangle. After getting these, we
can find the circumcenter of the triangle by a simple property stated as under:
The circumcenter of the triangle is point where all the perpendicular bisectors
of the sides of the triangle intersect.
1050
Chapter 189. Program to find Circumcenter of a Triangle
Note here that, there is no need to find all of the three sides of the triangle. Finding two
sides is sufficient as we can uniquely find the point of intersection using just two perpen-
dicular bisectors. The third perpendicular bisector will itself pass through the so found
circumcenter.
The things to be done can be divided as under:
1. Find 2 lines (say PQ and QR) which form the sides of the triangle.
2. Find the perpendicular bisectors of PQ and QR (say lines L and M respectively).
3. Find the point of intersection of lines L and M as the circumcenter of the given triangle.
STEP 1
Refer this post Program to find line passing through 2 Points
STEP 2
Let PQ be represented as ax + by = c
A line perpendicular to this line is represented as -bx + ay = d for some d.
However, we are interested in the perpendicular bisector. So, we find the mid-point of P
and Q and putting this value in the standard equation, we get the value of d.
Similarly, we repeat the process for QR.
d = -bx + ay
where, x = (xp + xq)/2
AND y = (yp + yq)/2
1051
Chapter 189. Program to find Circumcenter of a Triangle
STEP 3
Refer this post Program for Point of Intersection of Two Lines
1052
Chapter 189. Program to find Circumcenter of a Triangle
1053
Chapter 189. Program to find Circumcenter of a Triangle
// Driver code.
int main()
{
pdd P = make_pair(6, 0);
pdd Q = make_pair(0, 0);
pdd R = make_pair(0, 8);
findCircumCenter(P, Q, R);
return 0;
}
Output:
Source
https://www.geeksforgeeks.org/program-find-circumcenter-triangle-2/
1054
Chapter 190
Input : 2
Output : Circumference = 12.566
Input : 8
Output : Circumference = 50.264
In a circle, points lie in the boundary of a circle are at same distance from its center. This
distance is called radius. Circumference of a circle can simply be evaluated using following
formula.
Circumference = 2*pi*r
where r is the radius of circle
and value of pi = 3.1415.
1055
Chapter 190. Program to find Circumference of a Circle
C++
Python3
1056
Chapter 190. Program to find Circumference of a Circle
PI = 3.1415
# utility function
def circumference(r):
return (2 * PI * r)
# driver function
print ('%.3f' % circumference(5))
# This code is contributed by Saloni Gupta
Java
C#
1057
Chapter 190. Program to find Circumference of a Circle
double PI = 3.1415;
double cir = 2*PI*r;
return cir;
}
// driver function
public static void Main () {
double r = 5;
double result =
Math.Round(circumference(r)
* 1000) / 1000.0;
Console.WriteLine("Circumference = "
+ result);
}
}
// This article is contributed by anuj_67.
PHP
<?php
// PHP program to find
// circumference of circle
$PI= 3.1415;
function circumference($r)
{
global $PI;
$cir = 2 * $PI * $r;
return $cir;
}
// Driver Code
$r = 5;
echo "Circumference = ",
circumference($r);
// This code is contributed aj_36
?>
Output :
Circumference = 31.415
1058
Chapter 190. Program to find Circumference of a Circle
Source
https://www.geeksforgeeks.org/program-find-circumference-circle/
1059
Chapter 191
C = 4 * a
where a is the side length.
Examples :
input: 4
1060
Chapter 191. Program to find Perimeter / Circumference of Square and Rectangle
output: 16
input: 3
output: 12
C++
Java
1061
Chapter 191. Program to find Perimeter / Circumference of Square and Rectangle
int a = 5;
System.out.println("Circumference of " +
"a square is " +
obj.Circumference(a));
}
}
// This code is contributed
// by Anshika Goyal.
Python3
C#
1062
Chapter 191. Program to find Perimeter / Circumference of Square and Rectangle
}
// This code is contributed by vt_m.
PHP
<?php
// PHP program to find
// Circumference of a square
function Circumference($a)
{
return 4 * $a;
}
// Driver Code
$a = 5;
echo "Circumference of a ".
"square is ",
Circumference($a);
// This code is contributed by ajit
?>
Output :
Circumference Of a square is 20
Circumference of a rectangle:
C = 2 * (l + W)
where l is the length and W is the width.
Examples :
1063
Chapter 191. Program to find Perimeter / Circumference of Square and Rectangle
input: 2 4
output: 12
input: 4 6
output: 20
C++
Python3
1064
Chapter 191. Program to find Perimeter / Circumference of Square and Rectangle
print("Circumference of a" +
" rectangle is % d" % (c))
Java
C#
// C# Program to find
// circumference of a rectangle
using System;
class GFG
{
static int Circumference(int l,
int w)
{
return (2 * (l + w));
}
1065
Chapter 191. Program to find Perimeter / Circumference of Square and Rectangle
PHP
<?php
// Php Program to find
// Circumference of a rectangle
function Circumference($l,$w)
{
return (2 * ($l + $w));
}
// Driver code
$l = 8; $w = 4;
$c = Circumference($l, $w);
echo "Circumference of a ".
"rectangle is " ,$c ,"\n";
// This code is contributed by aj_36.
?>
Output :
Circumference of a rectangle is 24
Source
https://www.geeksforgeeks.org/python-program-find-perimeter-circumference-square-rectangle/
1066
Chapter 192
1067
Chapter 192. Program to find area of a Circular Segment
We are given radius of circle and angle that forms minor segment. We need to find areas of
two segments.
Examples :
Input :
radius = 21.0
angle = 120.0
Output :
Area of minor segment 270.855
Area of major segment 1114.59
Input :
radius = 10.0
angle = 90.0
Output :
Area of minor segment 28.5397
Area of major segment 285.619
1068
Chapter 192. Program to find area of a Circular Segment
For that, we join the end points of the chord with the center of the circle resulting in a
sector which subtends some ‘angle’ at the center. And a perpendicular is drawn from the
center of the circle on the chord AB. By congruence of triangles, we obtain that the � AOP
= � BOP = 1/2(angle).
1069
Chapter 192. Program to find area of a Circular Segment
So,
Base = AB = AP + PB
= 2 * AP
= 2 * r * Sin(X/2)
1070
Chapter 192. Program to find area of a Circular Segment
Height = OP = r * Cos(X/2)
C++
1071
Chapter 192. Program to find area of a Circular Segment
Java
Python
# Python3 Program
# to find area of
# segment of a
# circle
import math
pi = 3.14159
# Function to find
1072
Chapter 192. Program to find area of a Circular Segment
# area of segment
def area_of_segment(radius, angle):
# Calculating area of sector
area_of_sector = pi *
(radius * radius)
* (angle / 360)
# Calculating area of triangle
area_of_triangle = 1 / 2 *
(radius * radius) *
math.sin((angle * pi) / 180)
return area_of_sector - area_of_triangle;
# Driver Code
radius = 10.0
angle = 90.0
print("Area of minor segment =",
area_of_segment(radius, angle))
print("Area of major segment =",
area_of_segment(radius, (360 - angle)))
# This code is contributed by Smitha Dinesh Semwal
C#
1073
Chapter 192. Program to find area of a Circular Segment
// Driver Function
public static void Main()
{
float radius = 10.0f, angle = 90.0f;
Console.WriteLine("Area of minor segment = " +
area_of_segment(radius, angle));
Console.WriteLine("Area of major segment = " +
area_of_segment(radius, (360 - angle)));
}
}
// This code is contributed by vt_m.
PHP
<?php
// PHP Program to
// find area of
// segment of a
// circle
// Function to find
// area of segment
function area_of_segment($radius,
$angle)
{
$pi = 3.14159;
// Calculating area of sector
$area_of_sector = $pi * ($radius * $radius) *
($angle / 360);
// Calculating area of triangle
$area_of_triangle = 1 / 2 * ($radius * $radius)
* sin(($angle * $pi) / 180);
return $area_of_sector - $area_of_triangle;
}
// Driver Code
$radius = 10.0;
$angle = 90.0;
echo ("Area of minor segment = ");
echo( area_of_segment($radius, $angle));
echo("\n");
1074
Chapter 192. Program to find area of a Circular Segment
echo("Area of major segment = ");
echo(area_of_segment($radius, (360 - $angle)));
// This code is contributed by vt_m.
?>
Output :
Improved By : vt_m
Source
https://www.geeksforgeeks.org/program-find-area-circular-segment/
1075
Chapter 193
In the above figure CD || AB, so they form the bases and the other two sides i.e., AD and
BC form the legs.
The area of a trapezoid can be found by using this simple formula :
a = base
b = base
h = height
Examples :
1076
Chapter 193. Program to find area of a Trapezoid
Java
1077
Chapter 193. Program to find area of a Trapezoid
// Driver Code
public static void main (String[] args)
{
int base1 = 8, base2 = 10,
height = 6;
double area = Area(base1, base2,
height);
System.out.println("Area is: " + area);
}
}
Python3
C#
// C# program to calculate
// area of a trapezoid
using System;
class GFG
{
// Function for the area
static double Area(int b1,
int b2,
int h)
{
return ((b1 + b2) / 2) * h;
}
// Driver Code
public static void Main ()
{
int base1 = 8, base2 = 10,
1078
Chapter 193. Program to find area of a Trapezoid
height = 6;
double area = Area(base1, base2,
height);
Console.WriteLine("Area is: " + area);
}
}
// This code is contributed by vt_m
PHP
<?php
// PHP program to calculate
// area of a trapezoid
// Function for the area
function Area( $b1, $b2, $h)
{
return (($b1 + $b2) / 2) * $h;
}
// Driver Code
$base1 = 8; $base2 = 10;
$height = 6;
$area = Area($base1, $base2, $height);
echo("Area is: ");
echo($area);
// This code is contributed by vt_m.
?>
Output :
Improved By : vt_m
Source
https://www.geeksforgeeks.org/program-find-area-trapezoid/
1079
Chapter 194
Area = pi * r2
where r is radius of circle
#include <stdio.h>
#include <math.h>
#define PI 3.142
1080
Chapter 194. Program to find area of a circle
double findArea(int r)
{
return PI * pow(r, 2);
}
int main()
{
printf("Area is %f", findArea(5));
return 0;
}
Java
Python3
C#
1081
Chapter 194. Program to find area of a circle
PHP
<?php
// PHP program to find area
// of circle
function findArea( $r)
{
$PI =3.142;
return $PI * pow($r, 2);
}
// Driver Code
echo("Area is ");
echo(findArea(5));
return 0;
// This code is contributed by vt_m.
?>
Output:
Area is 78.550000
Improved By : vt_m
1082
Chapter 194. Program to find area of a circle
Source
https://www.geeksforgeeks.org/c-program-find-area-circle/
1083
Chapter 195
Examples :
Input : a = 5, b = 7, c = 8
Output : Area of a triangle is 17.320508
Input : a = 3, b = 4, c = 5
Output : Area of a triangle is 6.000000
Area = sqrt(s*(s-a)*(s-b)*(s-c))
where a, b and c are lengths of sides of
triangle and s = (a+b+c)/2
1084
Chapter 195. Program to find area of a triangle
C++
#include <stdio.h>
#include <stdlib.h>
float findArea(int a, int b, int c)
{
// Length of sides must be positive and sum of any two sides
// must be smaller than third side.
if (a < 0 || b < 0 || c <0 || (a+b <= c) ||
a+c <=b || b+c <=a)
{
printf("Not a valid trianglen");
exit(0);
}
int s = (a+b+c)/2;
return sqrt(s*(s-a)*(s-b)*(s-c));
}
int main()
{
int a = 3;
int b = 4;
int c = 5;
printf("Area is %f", findArea(a, b, c));
return 0;
}
Java
1085
Chapter 195. Program to find area of a triangle
// Floyd's triangle
class Test
{
static float findArea(int a, int b, int c)
{
// Length of sides must be positive and sum of any two sides
// must be smaller than third side.
if (a < 0 || b < 0 || c <0 || (a+b <= c) ||
a+c <=b || b+c <=a)
{
System.out.println("Not a valid triangle");
System.exit(0);
}
int s = (a+b+c)/2;
return (float)Math.sqrt(s*(s-a)*(s-b)*(s-c));
}
// Driver method
public static void main(String[] args)
{
int a = 3;
int b = 4;
int c = 5;
System.out.println("Area is " + findArea(a, b, c));
}
}
Python
1086
Chapter 195. Program to find area of a triangle
C#
// C# program to print
// Floyd's triangle
using System;
class Test {
// Function to find area
static float findArea(int a, int b,
int c)
{
// Length of sides must be positive
// and sum of any two sides
// must be smaller than third side.
if (a < 0 || b < 0 || c <0 ||
(a + b <= c) || a + c <=b ||
b + c <=a)
{
Console.Write("Not a valid triangle");
System.Environment.Exit(0);
}
int s = (a + b + c) / 2;
return (float)Math.Sqrt(s * (s - a) *
(s - b) * (s - c));
}
// Driver code
public static void Main()
{
int a = 3;
int b = 4;
int c = 5;
1087
Chapter 195. Program to find area of a triangle
PHP
<?php
function findArea($a, $b, $c)
{
// Length of sides must be positive
// and sum of any two sides must
// be smaller than third side.
if ($a < 0 or $b < 0 or
$c < 0 or ($a + $b <= $c) or
$a + $c <= $b or $b + $c <= $a)
{
echo "Not a valid trianglen";
exit(0);
}
$s = ($a + $b + $c) / 2;
return sqrt($s * ($s - $a) *
($s - $b) * ($s - $c));
}
// Driver Code
$a = 3;
$b = 4;
$c = 5;
echo "Area is ", findArea($a, $b, $c);
// This code is contributed anuJ_67.
?>
Output :
Area is 6
Area
1088
Chapter 195. Program to find area of a triangle
CPP
Java
1089
Chapter 195. Program to find area of a triangle
{
// Initialize area
double area = 0.0;
// Calculate value of shoelace formula
int j = n - 1;
for (int i = 0; i < n; i++)
{
area += (X[j] + X[i]) * (Y[j] - Y[i]);
// j is previous vertex to i
j = i;
}
// Return absolute value
return Math.abs(area / 2.0);
}
// Driver program
public static void main (String[] args)
{
double X[] = {0, 2, 4};
double Y[] = {1, 3, 7};
int n = X.length;
System.out.println(polygonArea(X, Y, n));
}
}
// This code is contributed
// by Nikita Tiwari.
Python3
1090
Chapter 195. Program to find area of a triangle
C#
1091
Chapter 195. Program to find area of a triangle
PHP
<?php
// PHP program to evaluate area of a
// polygon using shoelace formula
// (X[i], Y[i]) are coordinates
// of i'th point.
function polygonArea( $X, $Y, $n)
{
// Initialize area
$area = 0.0;
// Calculate value of
// shoelace formula
$j = $n - 1;
for ( $i = 0; $i < $n; $i++)
{
$area += ($X[$j] + $X[$i]) *
($Y[$j] - $Y[$i]);
// j is previous vertex to i
$j = $i;
}
// Return absolute value
return abs($area / 2.0);
}
// Driver Code
1092
Chapter 195. Program to find area of a triangle
Output :
Source
https://www.geeksforgeeks.org/c-program-find-area-triangle/
1093
Chapter 196
1094
Chapter 196. Program to find equation of a plane passing through 3 points
1095
Chapter 196. Program to find equation of a plane passing through 3 points
Examples:
Input: x1 = -1 y1 = w z1 = 1
x2 = 0 y2 = -3 z2 = 2
x3 = 1 y3 = 1 z3 = -4
Output: equation of plane is 26 x + 7 y + 9 z + 3 = 0.
Input: x1 = 2, y1 = 1, z1 = -1, 1
x2 = 0, y2 = -2, z2 = 0
x3 = 1, y3 = -1, z3 = 2
Output: equation of plane is -7 x + 5 y + 1 z + 10 = 0.
Approach: Let P, Q and R be the three points with coordinates (x1, y1, z1), (x2, y2, z2),
(x3, y3, z3) respectively. Then the equation of plane is a * (x – x0) + b * (y – y0) + c *
(z – z0) = 0, where a, b, c are direction ratios of normal to the plane and (x0, y0, z0) are
co-ordinates of any point(i.e P, Q, or R) passing through the plane. For finding direction
ratios of normal to the plane, take any two vectors in plane, let it be vector PQ, vector PR.
Direction ratios of normal vector will be a, b, c. Taking any one point from P, Q, or R, let
its co-ordinate be (x0, y0, z0). Then the equation of plane passing through a point(x0, y0,
z0) and having direction ratios a, b, c will be
1096
Chapter 196. Program to find equation of a plane passing through 3 points
// Function to find equation of plane.
void equation_plane(float x1, float y1, float z1, float x2,
float y2, float z2, float x3, float y3, float z3)
{
float a1 = x2 - x1;
float b1 = y2 - y1;
float c1 = z2 - z1;
float a2 = x3 - x1;
float b2 = y3 - y1;
float c2 = z3 - z1;
float a = b1 * c2 - b2 * c1;
float b = a2 * c1 - a1 * c2;
float c = a1 * b2 - b1 * a2;
float d = (- a * x1 - b * y1 - c * z1);
printf("equation of plane is %.2f x + %.2f"
" y + %.2f z + %.2f = 0.",a,b,c,d);
return;
}
// Driver Code
int main()
{
float x1 =-1;
float y1 = 2;
float z1 = 1;
float x2 = 0;
float y2 =-3;
float z2 = 2;
float x3 = 1;
float y3 = 1;
float z3 =-4;
equation_plane(x1, y1, z1, x2, y2, z2, x3, y3, z3);
return 0;
}
// This code is contributed
// by Amber_Saxena.
Java
1097
Chapter 196. Program to find equation of a plane passing through 3 points
Python
1098
Chapter 196. Program to find equation of a plane passing through 3 points
def equation_plane(x1, y1, z1, x2, y2, z2, x3, y3, z3):
a1 = x2 - x1
b1 = y2 - y1
c1 = z2 - z1
a2 = x3 - x1
b2 = y3 - y1
c2 = z3 - z1
a = b1 * c2 - b2 * c1
b = a2 * c1 - a1 * c2
c = a1 * b2 - b1 * a2
d = (- a * x1 - b * y1 - c * z1)
print "equation of plane is ",
print a, "x +",
print b, "y +",
print c, "z +",
print d, "= 0."
# Driver Code
x1 =-1
y1 = 2
z1 = 1
x2 = 0
y2 =-3
z2 = 2
x3 = 1
y3 = 1
z3 =-4
equation_plane(x1, y1, z1, x2, y2, z2, x3, y3, z3)
C#
// C# program to find equation
// of a plane passing through
// given 3 points.
using System;
class GFG
{
// Function to find equation of plane.
static void equation_plane(float x1, float y1,
float z1, float x2,
float y2, float z2,
float x3, float y3,
float z3)
{
float a1 = x2 – x1;
float b1 = y2 – y1;
1099
Chapter 196. Program to find equation of a plane passing through 3 points
float c1 = z2 – z1;
float a2 = x3 – x1;
float b2 = y3 – y1;
float c2 = z3 – z1;
float a = b1 * c2 – b2 * c1;
float b = a2 * c1 – a1 * c2;
float c = a1 * b2 – b1 * a2;
float d = (- a * x1 – b * y1 – c * z1);
Console.Write(“equation of plane is ” + a +
“x + ” + b + “y + ” + c +
“z + ” + d + ” = 0�);
}
// Driver code
public static void Main()
{
float x1 =-1;
float y1 = 2;
float z1 = 1;
float x2 = 0;
float y2 =-3;
float z2 = 2;
float x3 = 1;
float y3 = 1;
float z3 =-4;
equation_plane(x1, y1, z1,
x2, y2, z2,
x3, y3, z3);
}
}
// This code is contributed
// by ChitraNayal
PHP
<?php
// PHP program to find equation
// of a plane passing through
// given 3 points.
// Function to find equation of plane.
function equation_plane($x1, $y1, $z1,
$x2, $y2, $z2,
$x3, $y3, $z3)
{
$a1 = $x2 - $x1;
$b1 = $y2 - $y1;
$c1 = $z2 - $z1;
1100
Chapter 196. Program to find equation of a plane passing through 3 points
Output:
equation of plane is 26 x + 7 y + 9 z + 3 = 0.
Source
https://www.geeksforgeeks.org/program-to-find-equation-of-a-plane-passing-through-3-points/
1101
Chapter 197
Input : P(3, 2)
Q(2, 6)
Output : 4x + 1y = 14
Input : P(0, 1)
Q(2, 4)
Output : 3x + -2y = -2
Let the given two points be P(x1 , y1 ) and Q(x2 , y2 ). Now, we find the equation of line
formed by these points.
Any line can be represented as,
ax + by = c
Let the two points satisfy the given line. So, we have,
ax1 + by1 = c
ax2 + by2 = c
We can set the following values so that all the equations hold true,
a = y2 - y1
1102
Chapter 197. Program to find line passing through 2 Points
b = x1 - x2
c = ax1 + by1
These can be derived by first getting the slope directly and then finding the intercept of the
line. OR these can also be derived cleverly by a simple observation as under:
Derivation :
Thus, we now have the values of a, b and c which means that we have the line in the
coordinate plane.
1103
Chapter 197. Program to find line passing through 2 Points
else
{
cout << "The line passing through points P and Q is: "
<< a << "x + " << b << "y = " << c << endl;
}
}
// Driver code
int main()
{
pdd P = make_pair(3, 2);
pdd Q = make_pair(2, 6);
lineFromPoints(P, Q);
return 0;
}
Output:
Source
https://www.geeksforgeeks.org/program-find-line-passing-2-points/
1104
Chapter 198
Input : x1 = 4, y1 = 2,
x2 = 2, y2 = 5
Output : Slope is -1.5
Approach: To calculate the slope of a line you need only two points from that line, (x1,
y1) and (x2, y2). The equation used to calculate the slope from two points is:
1105
Chapter 198. Program to find slope of a line
c++
Java
Python
1106
Chapter 198. Program to find slope of a line
C#
PHP
<?php
// PHP program for
// slope of line
// function to find the
// slope of a straight line
function slope($x1, $y1, $x2, $y2)
{
return ($y2 - $y1) /
($x2 - $x1);
1107
Chapter 198. Program to find slope of a line
}
// Driver Code
$x1 = 4;
$y1 = 2;
$x2 = 2;
$y2 = 5;
echo "Slope is: "
, slope($x1, $y1,
$x2, $y2);
// This code is contributed by anuj_67.
?>
Output:
Improved By : vt_m
Source
https://www.geeksforgeeks.org/program-find-slope-line/
1108
Chapter 199
Program to find smallest difference of angles of two parts of a given circle - GeeksforGeeks
Given a division of circle into n pieces as an array of size n. The i-th element of the array
denotes the angle of one piece. Our task is to make two continuous parts from these pieces
so that the difference between angles of these two parts is minimum.
Examples :
We can notice that if one of the part is continuous then all the remaining pieces also form
a continuous part. If angle of the first part is equal to x then difference between angles of
first and second parts is |x – (360 – x)| = |2 * x – 360| = 2 * |x – 180|. So for each possible
1109
Chapter 199. Program to find smallest difference of angles of two parts of a given circle
C++
Java
1110
Chapter 199. Program to find smallest difference of angles of two parts of a given circle
Python3
1111
Chapter 199. Program to find smallest difference of angles of two parts of a given circle
import math
# function returns the minimum
# difference of angles.
def findMinimumAngle (arr, n):
l = 0
_sum = 0
ans = 360
for i in range(n):
#sum of array
_sum += arr[i]
while _sum >= 180:
# calculating the difference of
# angles and take minimum of
# previous and newly calculated
ans = min(ans, 2 * abs(180 - _sum))
_sum -= arr[l]
l+=1
ans = min(ans, 2 * abs(180 - _sum))
return ans
# driver code
arr = [100, 100, 160]
n = len(arr)
print(findMinimumAngle (arr, n))
# This code is contributed by "Abhishek Sharma 44"
C#
1112
Chapter 199. Program to find smallest difference of angles of two parts of a given circle
PHP
<?php
// PHP program to find minimum
// difference of angles of two
// parts of given circle.
// Returns the minimum difference
// of angles.
function findMinimumAngle($arr, $n)
{
$l = 0; $sum = 0; $ans = 360;
for ($i = 0; $i < $n; $i++)
{
// sum of array
$sum += $arr[$i];
1113
Chapter 199. Program to find smallest difference of angles of two parts of a given circle
Output :
40
Improved By : jit_t
Source
https://www.geeksforgeeks.org/program-find-smallest-difference-angles-two-parts-given-circle/
1114
Chapter 200
Input: l = 10, b = 8, h = 6
Output: Volume of triangular prism: 240
1115
Chapter 200. Program to find the Volume of a Triangular Prism
Volume = ( l * b * h ) / 2
C++
1116
Chapter 200. Program to find the Volume of a Triangular Prism
int main()
{
float l = 18, b = 12, h = 9;
// function calling
cout << "Volume of triangular prism: "
<< findVolume(l, b, h);
return 0;
}
Java
Python3
1117
Chapter 200. Program to find the Volume of a Triangular Prism
def findVolume(l, b, h) :
# formula to find Volume
return ((l * b * h) / 2)
# Driver Code
l = 18
b = 12
h = 9
# function calling
print("Volume of triangular prism: ",
findVolume(l, b, h))
C#
PHP
<?php
// PHP program to find the volume
1118
Chapter 200. Program to find the Volume of a Triangular Prism
Output:
Source
https://www.geeksforgeeks.org/program-to-find-the-volume-of-a-triangular-prism/
1119
Chapter 201
Input : x1 = –1, y1 = 2,
x2 = 3, y2 = –6
Output : 1,–2
Input : x1 = 6.4, y1 = 3
x2 = –10.7, y2 = 4
Output : –2.15, 3.5
The Midpoint Formula: The midpoint of two points, (x1, y2) and (x2, y2) is the point
M found by the following formula: M = ((x1 +x2 )/2 , (y1 +y2 )/2)
C++
1120
Chapter 201. Program to find the mid-point of a line
Java
1121
Chapter 201. Program to find the mid-point of a line
}
// This code is contributed by vt_m.
Python3
# Python3 program to find
# the midpoint of a line
# Function to find the
# midpoint of a line
def midpoint(x1, x2, y1, y2):
print((x1 + x2) // 2, " , ",
(y1 + y2) // 2)
# Driver Code
x1, y1, x2, y2 = -1, 2, 3, -6
midpoint(x1, x2, y1, y2)
# This code is contributed by Anant Agarwal.
C#
// C# program to find
// the midpoint of a line
using System;
class GFG
{
// function to find the
// midpoint of a line
static void midpoint(int x1, int x2,
int y1, int y2)
{
Console.WriteLine((x1 + x2) / 2 +
" , " + (y1 + y2) / 2) ;
}
// Driver code
public static void Main ()
{
int x1 =-1, y1 = 2 ;
int x2 = 3, y2 = -6 ;
midpoint(x1, x2, y1, y2);
1122
Chapter 201. Program to find the mid-point of a line
}
}
// This code is contributed by vt_m.
PHP
<?php
// PHP program to find
// the midpoint of a line
// function to find the
// midpoint of a line
function midpoint($x1, $x2, $y1, $y2)
{
echo((float)($x1 + $x2)/2 . " , " .
(float)($y1 + $y2)/2) ;
}
// Driver Code
$x1 = -1; $y1 = 2 ;
$x2 = 3; $y2 = -6 ;
midpoint($x1, $x2, $y1, $y2);
// This code is contributed by Ajit.
?>
Output :
1 , -2
Improved By : jit_t
Source
https://www.geeksforgeeks.org/program-find-mid-point-line/
1123
Chapter 202
Pythagorean Quadruple
a = m 2 + n 2 – p 2 – q2 ,
b = 2(mq + np),
c = 2(nq – mp),
d = m 2 + n 2 + p2 + q 2
where m, n, p, q are non-negative integers with greatest common divisor 1 such that m
+ n + p + q are odd. Thus, all primitive Pythagorean quadruples are characterized by
Lebesgue’s identity.
1124
Chapter 202. Pythagorean Quadruple
C++
Java
1125
Chapter 202. Pythagorean Quadruple
}
// Driver function
public static void main (String[] args) {
int a = 1, b = 2, c = 2, d = 3;
if (pythagorean_quadruple(a, b, c, d))
System.out.println("Yes");
else
System.out.println("No" );
}
}
// This code is contributed by Gitanjali.
Python3
C#
// C# code to detect
// Pythagorean Quadruples.
using System;
1126
Chapter 202. Pythagorean Quadruple
class GFG {
// function for checking
static Boolean pythagorean_quadruple(int a,
int b, int c, int d)
{
int sum = a * a + b * b + c * c;
if (d * d == sum)
return true;
else
return false;
}
// Driver function
public static void Main () {
int a = 1, b = 2, c = 2, d = 3;
if (pythagorean_quadruple(a, b, c, d))
Console.WriteLine("Yes");
else
Console.WriteLine("No" );
}
}
// This code is contributed by vt_M.
PHP
<?php
// php code to detect Pythagorean Quadruples.
// function for checking
function pythagorean_quadruple($a, $b, $c, $d)
{
$sum = $a * $a + $b * $b + $c * $c;
if ($d * $d == $sum)
return true;
else
return false;
}
// Driver Code
$a = 1; $b = 2; $c = 2; $d = 3;
1127
Chapter 202. Pythagorean Quadruple
Output:
Yes
References
Wiki
mathworld
Improved By : vt_m
Source
https://www.geeksforgeeks.org/pythagorean-quadruple/
1128
Chapter 203
Input : n = 5
Coordinates:
1 1
2 2
3 3
-1 -1
4 4
Query 1: 3
Query 2: 32
Output :
3
5
For first query radius = 3, number of points lie
inside or on the circumference are (1, 1), (-1, -1),
(2, 2). There are only 3 points lie inside or on
the circumference of the circle.
For second query radius = 32, all five points are
inside the circle.
1129
Chapter 203. Queries on count of points lie inside a circle
The equation for the circle centered at origin (0, 0) with radius r, x2 + y2 = r2 . And
condition for a point at (x1 , y1 ) to lie inside or on the circumference, x1 2 + y1 2 <= r2 .
A Naive approach can be for each query, traverse through all points and check the condi-
tion. This take O(n*Q) time complexity.
An Efficient approach is to precompute x2 + y2 for each point coordinate and store them
in an array p[]. Now, sort the array p[]. Then apply binary search on the array to find last
index with condition p[i] <= r2 for each query.
Below is the implementation of this approach:
C++
1130
Chapter 203. Queries on count of points lie inside a circle
return end + 1;
else
return start + 1;
}
// Driven Program
int main()
{
int x[] = { 1, 2, 3, -1, 4 };
int y[] = { 1, 2, 3, -1, 4 };
int n = sizeof(x) / sizeof(x[0]);
// Compute distances of all points and keep
// the distances sorted so that query can
// work in O(logn) using Binary Search.
int p[n];
preprocess(p, x, y, n);
// Print number of points in a circle of radius 3.
cout << query(p, n, 3) << endl;
// Print number of points in a circle of radius 32.
cout << query(p, n, 32) << endl;
return 0;
}
Java
1131
Chapter 203. Queries on count of points lie inside a circle
1132
Chapter 203. Queries on count of points lie inside a circle
C#
1133
Chapter 203. Queries on count of points lie inside a circle
{
int[] x = { 1, 2, 3, -1, 4 };
int[] y = { 1, 2, 3, -1, 4 };
int n = x.Length;
// Compute distances of all points and keep
// the distances sorted so that query can
// work in O(logn) using Binary Search.
int[] p = new int[n];
preprocess(p, x, y, n);
// Print number of points in a circle of
// radius 3.
Console.WriteLine(query(p, n, 3));
// Print number of points in a circle of
// radius 32.
Console.WriteLine(query(p, n, 32));
}
}
// This code is contributed by vt_m.
Output:
3
5
Time Complexity: O(n log n) for preprocessing and O(Q Log n) for Q queries.
Improved By : vt_m
Source
https://www.geeksforgeeks.org/queries-count-point-lie-inside-circle/
1134
Chapter 204
Input is an array of points specified by their x and y coordinates. Output is a convex hull
of this set of points in ascending order of x coordinates.
Example :
Input : points[] = {{0, 3}, {1, 1}, {2, 2}, {4, 4},
{0, 0}, {1, 2}, {3, 1}, {3, 3}};
Output : The points in convex hull are:
(0, 0) (0, 3) (3, 1) (4, 4)
Input : points[] = {(0, 0), (0, 4), (-4, 0), (5, 0),
(0, -6), (1, 0)};
Output : (-4, 0), (5, 0), (0, -6), (0, 4)
1135
Chapter 204. Quickhull Algorithm for Convex Hull
1. Find the point with minimum x-coordinate lets say, min_x and similarly the point
with maximum x-coordinate, max_x.
2. Make a line joining these two points, say L. This line will divide the the whole set into
two parts. Take both the parts one by one and proceed further.
3. For a part, find the point P with maximum distance from the line L. P forms a triangle
with the points min_x, max_x. It is clear that the points residing inside this triangle
can never be the part of convex hull.
4. The above step divides the problem into two sub-problems (solved recursively). Now
the line joining the points P and min_x and the line joining the points P and max_x
are new lines and the points residing outside the triangle is the set of points. Repeat
point no. 3 till there no point left with the line. Add the end points of this point to
the convex hull.
Below is C++ implementation of above idea. The implementation uses set to store points
so that points can be printed in sorted order. A point is represented as a pair.
1136
Chapter 204. Quickhull Algorithm for Convex Hull
// Returns the square of distance between
// p1 and p2.
int dist(iPair p, iPair q)
{
return (p.second - q.second) * (p.second - q.second) +
(p.first - q.first) * (p.first - q.first);
}
// returns a value proportional to the distance
// between the point p and the line joining the
// points p1 and p2
int lineDist(iPair p1, iPair p2, iPair p)
{
return abs ((p.second - p1.second) * (p2.first - p1.first) -
(p2.second - p1.second) * (p.first - p1.first));
}
// End points of line L are p1 and p2. side can have value
// 1 or -1 specifying each of the parts made by the line L
void quickHull(iPair a[], int n, iPair p1, iPair p2, int side)
{
int ind = -1;
int max_dist = 0;
// finding the point with maximum distance
// from L and also on the specified side of L.
for (int i=0; i<n; i++)
{
int temp = lineDist(p1, p2, a[i]);
if (findSide(p1, p2, a[i]) == side && temp > max_dist)
{
ind = i;
max_dist = temp;
}
}
// If no point is found, add the end points
// of L to the convex hull.
if (ind == -1)
{
hull.insert(p1);
hull.insert(p2);
return;
}
// Recur for the two parts divided by a[ind]
quickHull(a, n, a[ind], p1, -findSide(a[ind], p1, p2));
1137
Chapter 204. Quickhull Algorithm for Convex Hull
1138
Chapter 204. Quickhull Algorithm for Convex Hull
printHull(a, n);
return 0;
}
Input :
Time Complexity: The analysis is similar to Quick Sort. On average, we get time com-
plexity as O(n Log n), but in worst case, it can become O(n2 )
Source
https://www.geeksforgeeks.org/quickhull-algorithm-convex-hull/
1139
Chapter 205
What is Rotation?
In Euclidean geometry, a rotation of axes in two dimensions is a mapping from an xy-
Cartesian coordinate system to an x’y’-Cartesian coordinate system in which the origin is
kept fixed and the x’ and y’ axes are obtained by rotating the x and y axes through an
angle �.
How to Perform Rotation?
Rotation can be interpreted as multiplying (rotating in anticlockwise direction) or dividing
(rotating in clockwise direction) every point of the coordinate system by a constant vector.
Note here that if we want to rotate a point by � in the anticlockwise direction about the
origin, we multiply it by polar (1.0, �) as discussed in SET 1. Similarly, we divide by polar
(1.0, �) to rotate the point by � in the clockwise direction.
After the rotation, required computations are performed and rotation is nullified by dividing
or multiplying every point by the constant vector respectively.
So, we have to reflect a point P about a line specified by points A and B denoted as AB.
Since, we know that the conjugate of a point is the reflection of the point about X-Axis. In
order to be able to use this fact, we will first perform translation (making A as the origin in
the new system) and then rotating the coordinate axes in such a way that the line becomes
the X-Axis in the new coordinate system.
Now we can simply apply the formula for reflection about X-Axis and then nullify the effects
of rotation and translation to get the final result.
1140
Chapter 205. Reflection of a point about a line in C++
Pt = P – A
Bt = B – A
At is origin
Pr = Pt/Bt
Prreflected = conj(Pr)
Ptreflected= conj(Pr)*Bt
Thus,
return conj(Pr)*Bt + A
where, Bt = B – A
Pt = P – A
Pr = Pt/Bt
1141
Chapter 205. Reflection of a point about a line in C++
1142
Chapter 205. Reflection of a point about a line in C++
{
// Performing translation and shifting origin at A
point Pt = P-A;
point Bt = B-A;
// Performing rotation in clockwise direction
// BtAt becomes the X-Axis in the new coordinate system
point Pr = Pt/Bt;
// Reflection of Pr about the new X-Axis
// Followed by restoring from rotation
// Followed by restoring from translation
return conj(Pr)*Bt + A;
}
int main()
{
// Rotate P about line AB
point P(4.0, 7.0);
point A(1.0, 1.0);
point B(3.0, 3.0);
point P_reflected = reflect(P, A, B);
cout << "The point P on reflecting about AB becomes:";
cout << "P_reflected"; displayPoint(P_reflected);
return 0;
}
Output:
Source
https://www.geeksforgeeks.org/reflection-point-line-c/
1143
Chapter 206
Input : x1 = 0, y1 = 0, x2 = 1, y2 = 1
Output : (2, 2)
Input : x1 = 1, y1 = 1, x2 = 2, y2 = 2
Output : (3, 3)
Let the reflection point of point (x1 , y1 ) about (x2 , y2 ) be (x’, y’).
For (x’, y’) be the 180 degree rotation of point (x1 , y1 ) around point (x2 , y2 ), they all must
be collinear i.e all the three point must lie on a same straight line. Also, observe (x2 , y2 )
will became mid point between (x1 , y1 ) and (x’, y’).
1144
Chapter 206. Reflection of a point at 180 degree rotation of another point
So,
x’ – x2 = x2 – x1
y’ – y2 = y2 – y1
x’ = 2 * x2 – x1
y’ = 2 * y2 – y1
Below is the implementation of this approach:
C++
Java
1145
Chapter 206. Reflection of a point at 180 degree rotation of another point
static void findPoint(int x1, int y1,
int x2, int y2)
{
System.out.println("(" + (int)(2 * x2 - x1)
+ "," + (int)(2 * y2 - y1 ) + " )");
}
// Driver code
public static void main(String args[])
{
int x1 = 0, y1 = 0, x2 = 1, y2 = 1;
findPoint(x1, y1, x2, y2);
}
}
// This code is contributed by Arnab Kundu.
C#
PHP
<?php
1146
Chapter 206. Reflection of a point at 180 degree rotation of another point
Output:
(2, 2)
Source
https://www.geeksforgeeks.org/reflection-point-180-degree-rotation-another-point/
1147
Chapter 207
We can solve this problem by getting a relation between the number of vertices a possible
polygon can have and total number of values in the array. Let a possible regular polygon
in circle has K vertices or K sides then it should satisfy two things to be the answer,
If given array size is N, then K should divide N otherwise K vertices can’t divide N vertices
in an equally manner to be a regular polygon.
Next thing is there should be one at every vertex of chosen polygon.
After above points, we can see that for solving this problem we need to iterate over
1148
Chapter 207. Regular polygon using only 1s in a binary numbered circle
divisors of N and then check whether every value of the array at chosen divisor’s dis-
tance is 1 or not. If it is 1 then we found our solution. We can iterate over all divisors in
O(sqrt(N)) time just by iterating over from 1 to sqrt(N). you can read more about that here.
C++
1149
Chapter 207. Regular polygon using only 1s in a binary numbered circle
Java
1150
Chapter 207. Regular polygon using only 1s in a binary numbered circle
}
/* 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 */
if (val != 0 && N/midpoints > 2)
{
System.out.println("Polygon possible with side length " +
N/midpoints);
return true;
}
}
return false;
}
// method prints sides in the polygon or print not
// possible in case of no possible polygon
static void isPolygonPossible(int arr[], int N)
{
// limit for iterating over divisors
int limit = (int)Math.sqrt(N);
for (int i = 1; i <= limit; i++)
{
// If i divides N then i and (N/i) will
// be divisors
if (N % i == 0)
{
// check polygon for both divisors
if (checkPolygonWithMidpoints(arr, N, i) ||
checkPolygonWithMidpoints(arr, N, (N/i)))
return;
}
}
System.out.println("Not possible");
}
// Driver method
public static void main(String args[])
{
int arr[] = {1, 0, 1, 0, 1, 0, 1, 0, 1, 1};
isPolygonPossible(arr, arr.length);
}
}
C#
1151
Chapter 207. Regular polygon using only 1s in a binary numbered circle
1152
Chapter 207. Regular polygon using only 1s in a binary numbered circle
PHP
<?php
// PHP program to find whether
// a regular polygon is possible
// in circle with 1s as vertices
// method returns true if polygon
// is possible with 'midpoints'
// number of midpoints
function checkPolygonWithMidpoints($arr, $N,
1153
Chapter 207. Regular polygon using only 1s in a binary numbered circle
$midpoints)
{
// loop for getting first
// vertex of polygon
for ($j = 0; $j < $midpoints; $j++)
{
$val = 1;
// loop over array values
// at 'midpoints' distance
for ($k = $j; $k < $N; $k += $midpoints)
{
// and(&) all those values,
// if even one of them is 0,
// val will be 0
$val &= $arr[$k];
}
/* 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 */
if ($val && $N / $midpoints > 2)
{
echo "Polygon possible with side length " ,
($N / $midpoints) , "\n";
return true;
}
}
return false;
}
// method prints sides in
// the polygon or print not
// possible in case of no
// possible polygon
function isPolygonPossible($arr, $N)
{
// limit for iterating
// over divisors
$limit = sqrt($N);
for ($i = 1; $i <= $limit; $i++)
{
// If i divides N then
// i and (N/i) will be
// divisors
if ($N % $i == 0)
1154
Chapter 207. Regular polygon using only 1s in a binary numbered circle
{
// check polygon for
// both divisors
if (checkPolygonWithMidpoints($arr, $N, $i) ||
checkPolygonWithMidpoints($arr, $N, ($N / $i)))
return;
}
}
echo "Not possiblen";
}
// Driver Code
$arr = array(1, 0, 1, 0, 1,
0, 1, 0, 1, 1);
$N = sizeof($arr);
isPolygonPossible($arr, $N);
// This code is contributed by ajit
?>
Output:
Improved By : jit_t
Source
https://www.geeksforgeeks.org/regular-polygon-using-1s-binary-numbered-circle/
1155
Chapter 208
Represent a given set of points by the best possible straight line - GeeksforGeeks
Find the value of m and c such that a straight line y = mx + c, best represents the equation
of a given set of points (x , y ), (x , y ), (x , y ), ……., (x , y ), given n >=2.
Examples:
Input : n = 5
x = 1, x = 2, x = 3,
x = 4, x = 5
y = 14, y = 27, y = 40,
y = 55, y = 68
Output : m = 13.6
c = 0
If we take any pair of number ( x, y )
from the given data, these value of m and c
should make it best fit into the equation
for a straight line, y = mx + c. Take x = 1
and y = 14, then using values
of m and c from the output, and putting it
in the following equation,
y = mx + c,
L.H.S.: y = 14, R.H.S: mx + c = 13.6 x 1 + 0 = 13.6
So, they are approximately equal.
Now, take x = 3 and y = 40,
L.H.S.: y = 40, R.H.S: mx + c = 13.6 x 3 + 0 = 40.8
So, they are also approximately equal, and so on
for all other values.
1156
Chapter 208. Represent a given set of points by the best possible straight line
Input : n = 6
x = 1, x = 2, x = 3,
x = 4, x = 5, x = 6
y = 1200, y = 900, y = 600,
y = 200, y = 110, y = 50
Output : m = -243.42
c = 1361.97
Approach
To best fit a set of points in an equation for a straight line, we need to find the value of
two variables, m and c. Now, since there are 2 unknown variables and depending upon the
value of n, two cases are possible –
Case 1 – When n = 2 : There will be two equations and two unknown variables to find,
so, there will be a unique solution .
Case 2 – When n > 2 : In this case, there may or may not exist values of m and c, which
satisfy all the n equations, but we can find the best possible values of m and c which can fit
a straight line in the given points .
So, if we have n different pairs of x and y, then, we can form n no. of equations from them
for a straight line, as follows
f = mx + c,
f = mx + c,
f = mx + c,
......................................,
......................................,
f = mx + c,
where, f, is the value
obtained by putting x in equation
mx + c.
Then, since ideally f should be same as y , but still we can find the f closest to y in all
the cases, if we take a new quantity, U = ?(y – f ) , and make this quantity minimum
for all value of i from 1 to n.
Note:(y – f ) is used in place of (y – f ), as we want to consider both the cases when
f or when y is greater, and we want their difference to be minimum, so if we would not
square the term, then situations in which f
is greater and situation in which y is greater will ancel each other to an extent, and this is
not what we want. So, we need to square the term.
Now, for U to be minimum, it must satisfy the following two equations –
= 0 and
= 0.
1157
Chapter 208. Represent a given set of points by the best possible straight line
?y = nc + m?x, and
?xy = c?x + m?x, which can be rearranged as -
m = (n * ?xy - ?x?y) / (n * ?x - (?x)), and
c = (?y - m?x) / n,
So, this is how values of m and c for both the cases are obtained, and we can represent a
given set of points, by the best possible straight line.
The following code implements the above given algorithm –
C
1158
Chapter 208. Represent a given set of points by the best possible straight line
C++
Java
1159
Chapter 208. Represent a given set of points by the best possible straight line
Python3
1160
Chapter 208. Represent a given set of points by the best possible straight line
m = (float)((n * sum_xy - sum_x * sum_y)
/ (n * sum_x2 - pow(sum_x, 2)));
c = (float)(sum_y - m * sum_x) / n;
print("m = ", m);
print("c = ", c);
# Driver main function
x = [1, 2, 3, 4, 5 ]
y = [ 14, 27, 40, 55, 68]
n = len(x)
bestApproximate(x, y, n)
# This code is contributed by Sam007.
C#
1161
Chapter 208. Represent a given set of points by the best possible straight line
}
// Driver main function
public static void Main()
{
int[] x = { 1, 2, 3, 4, 5 };
int[] y = { 14, 27, 40, 55, 68 };
// Function calling
bestApproximate(x, y);
}
}
// This code is contributed by Sam007
PHP
<?php
// PHP Program to find m and c
// for a straight line given,
// x and y
// function to calculate m and
// c that best fit points
// represented by x[] and y[]
function bestApproximate($x, $y, $n)
{
$i; $j;
$m; $c;
$sum_x = 0;
$sum_y = 0;
$sum_xy = 0;
$sum_x2 = 0;
for ($i = 0; $i < $n; $i++)
{
$sum_x += $x[$i];
$sum_y += $y[$i];
$sum_xy += $x[$i] * $y[$i];
$sum_x2 += ($x[$i] * $x[$i]);
}
$m = ($n * $sum_xy - $sum_x * $sum_y) /
($n * $sum_x2 - ($sum_x * $sum_x));
$c = ($sum_y - $m * $sum_x) / $n;
echo "m =", $m;
echo "\nc =", $c;
}
1162
Chapter 208. Represent a given set of points by the best possible straight line
// Driver Code
$x =array(1, 2, 3, 4, 5);
$y =array (14, 27, 40, 55, 68);
$n = sizeof($x);
bestApproximate($x, $y, $n);
// This code is contributed by ajit
?>
Output:
m=13.6
c=0.0
Source
https://www.geeksforgeeks.org/represent-given-set-points-best-possible-straight-line/
1163
Chapter 209
1164
Chapter 209. Rotation of a point about another point in C++
So, for rotating P about Q, we shift the origin at Q i.e. we subtract the vector equivalent
of Q from every point of the coordinate plane. Now the new point P – Q has to be rotated
about the origin and then translation has to be nullified.
These steps can be described as under:
1. Translation (Shifting origin at Q): Subtract Q from all points. Thus, P becomes
P–Q
2. Rotation of (P – Q) about origin: (P – Q) * polar(1.0, �)
3. Restoring back the Origin: Add Q to all the points.
Thus,
1165
Chapter 209. Rotation of a point about another point in C++
#include <complex>
using namespace std;
typedef complex<double> point;
#define x real()
#define y imag()
// Constant PI for providing angles in radians
#define PI 3.1415926535897932384626
// Function used to display X and Y coordinates of a point
void displayPoint(point P)
{
cout << "(" << P.x << ", " << P.y << ")" << endl;
}
//Function for Rotation of P about Q by angle theta
point rotate(point P, point Q, double theta)
{
return (P-Q) * polar(1.0, theta) + Q;
}
int main()
{
// Rotate P about Q
point P(4.0, 3.0);
point Q(2.0, 2.0);
// Angle of rotation = 90 degrees
double theta = PI/2;
point P_rotated = rotate(P, Q, theta);
cout << "The point P on rotating 90 degrees anti-clockwise about Q becomes:";
cout << "P_rotated"; displayPoint(P_rotated);
return 0;
}
Output:
Source
https://www.geeksforgeeks.org/rotation-of-a-point-about-another-point-in-cpp/
1166
Chapter 210
Examples:
Input : x1 = 1, y1 = 0, x2 = 2 y2 = 5,
m = 1, n = 1
Output : (1.5, 2.5)
Explanation: co-ordinates (1.5, 2.5)
1167
Chapter 210. Section formula (Point that divides a line in given ratio)
Input : x1 = 2, y1 = 4, x2 = 4, y2 = 6,
m = 2, n = 3
Output : (2.8, 4.8)
Explanation: (2.8, 4.8) divides the line
in the ratio 2:3
The section formula tells us the coordinates of the point which divides a given line segment
into two parts such that their lengths are in the ratio m : n
C++
1168
Chapter 210. Section formula (Point that divides a line in given ratio)
return 0;
}
Java
Python
1169
Chapter 210. Section formula (Point that divides a line in given ratio)
x2 = 4
y1 = 4
y2 = 6
m = 2
n = 3
section(x1, x2, y1, y2, m, n)
C#
PHP
<?php
1170
Chapter 210. Section formula (Point that divides a line in given ratio)
Output:
(2.8, 4.8)
1171
Chapter 210. Section formula (Point that divides a line in given ratio)
We are given,
PR/QR = m/n
References:
http://doubleroot.in/lessons/coordinate-geometry-basics/section-formula/#.WjYXQvbhU8o
Improved By : jit_t
Source
https://www.geeksforgeeks.org/section-formula-point-divides-line-given-ratio/
1172
Chapter 211
Consider a point C and a line that passes through A and B as shown in the below figure.
1173
Chapter 211. Shortest distance between a Line and a Point in a 3-D plane
Now Consider the vectors, AB and AC and the shortest distance as CD. The Shortest
Distance is always the perpendicular distance. The point D is taken on AB such that CD
is perpendicular to AB.
1174
Chapter 211. Shortest distance between a Line and a Point in a 3-D plane
Note: In the case when D does not fall on line segment AB there will be a point D’ such
that PD’ is perpendicular to AB and D’ lies on line segment AB with CD = PD’.
The magnitude of cross product AB and AC gives the Area of the parallelogram. Also, the
area of a parallelogram is Base * Height = AB * CD. So,
CD = |ABxAC| / |AB|
1175
Chapter 211. Shortest distance between a Line and a Point in a 3-D plane
}
Vector operator+(Vector v); // ADD 2 Vectors
Vector operator-(Vector v); // Subtraction
int operator^(Vector v); // Dot Product
Vector operator*(Vector v); // Cross Product
float magnitude()
{
return sqrt(pow(x, 2) + pow(y, 2) + pow(z, 2));
}
friend ostream& operator<<(ostream& out, const Vector& v);
// To output the Vector
};
// ADD 2 Vectors
Vector Vector::operator+(Vector v)
{
int x1, y1, z1;
x1 = x + v.x;
y1 = y + v.y;
z1 = z + v.z;
return Vector(x1, y1, z1);
}
// Subtract 2 vectors
Vector Vector::operator-(Vector v)
{
int x1, y1, z1;
x1 = x - v.x;
y1 = y - v.y;
z1 = z - v.z;
return Vector(x1, y1, z1);
}
// Dot product of 2 vectors
int Vector::operator^(Vector v)
{
int x1, y1, z1;
x1 = x * v.x;
y1 = y * v.y;
z1 = z * v.z;
return (x1 + y1 + z1);
}
// Cross product of 2 vectors
Vector Vector::operator*(Vector v)
{
int x1, y1, z1;
x1 = y * v.z - z * v.y;
1176
Chapter 211. Shortest distance between a Line and a Point in a 3-D plane
Output:
1177
Chapter 211. Shortest distance between a Line and a Point in a 3-D plane
Source
https://www.geeksforgeeks.org/shortest-distance-between-a-line-and-a-point-in-a-3-d-plane/
1178
Chapter 212
Input : 5
Output : Slope of perpendicular line is : -0.20
Input : 4
Output : Slope of perpendicular line is : -0.25
Suppose we are given two perpendicular line segments AB and CD. The slope of AB is m1
and line CD is m2 .
m1 * m2 = -1
From above, we can say
m2 = – 1/( m1 ) .
1179
Chapter 212. Slope of perpendicular to line
C++
1180
Chapter 212. Slope of perpendicular to line
return -1.0 / m;
}
int main()
{
double m = 2.0;
cout << findPCSlope(m);
return 0;
}
Java
Python 3
1181
Chapter 212. Slope of perpendicular to line
# This code is contributed
# by Smitha
C#
PHP
<?php
// PHP program find slope
// of perpendicular line
// Function to find the
// Slope of other line
function findPCSlope($m)
{
return -1.0 / $m;
}
// Driver Code
$m = 2.0;
echo findPCSlope($m);
1182
Chapter 212. Slope of perpendicular to line
Output:
-0.5
Source
https://www.geeksforgeeks.org/slope-perpendicular-line/
1183
Chapter 213
Input : 1 2
Output : 4
We can form a 2 x 2 square
using two rectangles of size
1 x 2.
Input : 7 10
Output :4900
Let’s say we want to make a square of side length a from rectangles of length l & b. This
means that a is a multiple of both l & b. Since we want the smallest square, it has to be
the lowest common multiple (LCM) of l & b.
Program 1:
1184
Chapter 213. Smallest square formed with given rectangles
Output:
144
1185
Chapter 213. Smallest square formed with given rectangles
Source
https://www.geeksforgeeks.org/smallest-square-formed-with-given-rectangles/
1186
Chapter 214
Input : a = { 3, 4, 5, 6 }
Output : 15
Explanation :
We can reduce 4 to 3 and 6 to 5 so that we got
rectangle of (3 * 5). Hence area = 15.
Input : a = { 3, 2, 5, 2 }
Output : 0
Naive Approach : Check for all possible four elements of the array and then whichever can
form a rectangle. In these rectangles, separate all those rectangles which are of maximum
area formed by these elements. After getting the rectangles and their areas, sum them all
to get our desired solution.
1187
Chapter 214. Sum of Areas of Rectangles possible for an array
Efficient Approach : To get the maximum area rectangle, first sort the elements of the
array in non-increasing array. After sorting, start the procedure to select the elements of
the array. Here, selection of two elements of array (as length of rectangle) is possible if
elements of array are equal (a[i] == a[i+1]) or if length of smaller element a[i+1] is one less
than a[i] (in this case we have our length a[i+1] because a[i] is decreased by 1). One flag
variable is maintained to check that whether we get length and breadth both. After getting
length, set the flag variable, now calculate the breadth in the same way as we have done for
length and sum the area of rectangle. After getting length and breadth both, again set the
flag variable false so that we will now search for a new rectangle. This process is repeated
and lastly, final sum of area is returned.
C++
1188
Chapter 214. Sum of Areas of Rectangles possible for an array
1189
Chapter 214. Sum of Areas of Rectangles possible for an array
// Driver code
int main()
{
int a[] = { 10, 10, 10, 10,
11, 10, 11, 10,
9, 9, 8, 8 };
int n = sizeof(a) / sizeof(a[0]);
cout << MaxTotalRectangleArea(a, n);
return 0;
}
Java
1190
Chapter 214. Sum of Areas of Rectangles possible for an array
1191
Chapter 214. Sum of Areas of Rectangles possible for an array
Python3
1192
Chapter 214. Sum of Areas of Rectangles possible for an array
if(i != 0) :
i = i + 1
# Selecting the length of
# rectangle so that difference
# between any two number is 1
# only. Here length is selected
# so flag is set
if ((a[i] == a[i + 1] or
a[i] - a[i + 1] == 1)
and flag == False) :
# flag is set means
# we have got length of
# rectangle
flag = True
# length is set to
# a[i+1] so that if
# a[i+1] is less than a[i]
# by 1 then also we have
# the correct chice for length
len = a[i + 1]
# incrementing the counter
# one time more as we have
# considered a[i+1] element
# also so.
i = i + 1
# Selecting the width of rectangle
# so that difference between any
# two number is 1 only. Here width
# is selected so now flag is again
# unset for next rectangle
elif ((a[i] == a[i + 1] or
a[i] - a[i + 1] == 1)
and flag == True) :
# area is calculated for
# rectangle
sum = sum + a[i + 1] * len
# flag is set false
# for another rectangle
# which we can get from
# elements in array
flag = False
1193
Chapter 214. Sum of Areas of Rectangles possible for an array
# incrementing the counter
# one time more as we have
# considered a[i+1] element
# also so.
i = i + 1
return sum
# Driver code
a = [ 10, 10, 10, 10, 11, 10,
11, 10, 9, 9, 8, 8 ]
n = len(a)
print (MaxTotalRectangleArea(a, n))
# This code is contributed by
# Manish Shaw (manishshaw1)
C#
1194
Chapter 214. Sum of Areas of Rectangles possible for an array
// Selecting the length of
// rectangle so that difference
// between any two number is 1
// only. Here length is selected
// so flag is set
if ((a[i] == a[i + 1] || a[i] -
a[i + 1] == 1) && (!flag))
{
// flag is set means
// we have got length of
// rectangle
flag = true;
// length is set to
// a[i+1] so that if
// a[i] a[i+1] is less
// than by 1 then also
// we have the correct
// choice for length
len = a[i + 1];
// incrementing the counter
// one time more as we have
// considered a[i+1] element
// also so.
i++;
}
// Selecting the width of rectangle
// so that difference between any
// two number is 1 only. Here width
// is selected so now flag is again
// unset for next rectangle
else if ((a[i] == a[i + 1] ||
a[i] - a[i + 1] == 1) && (flag))
{
// area is calculated for
// rectangle
sum = sum + a[i + 1] * len;
// flag is set false
// for another rectangle
// which we can get from
// elements in array
flag = false;
// incrementing the counter
1195
Chapter 214. Sum of Areas of Rectangles possible for an array
PHP
<?php
// PHP code to find sum
// of all area rectangle
// possible
// Function to find
// area of rectangles
function MaxTotalRectangleArea( $a, $n)
{
// sorting the array in
// descending order
rsort($a);
// store the final sum of
// all the rectangles area
// possible
$sum = 0;
$flag = false;
// temporary variable to store
// the length of rectangle
1196
Chapter 214. Sum of Areas of Rectangles possible for an array
$len;
for ( $i = 0; $i < $n; $i++)
{
// Selecting the length of
// rectangle so that difference
// between any two number is 1
// only. Here length is selected
// so flag is set
if (($a[$i] == $a[$i + 1] or $a[$i] -
$a[$i + 1] == 1) and (!$flag))
{
// flag is set means
// we have got length of
// rectangle
$flag = true;
// length is set to
// a[i+1] so that if
// a[i+1] is less than a[i]
// by 1 then also we have
// the correct chice for length
$len = $a[$i + 1];
// incrementing the counter
// one time more as we have
// considered a[i+1] element
// also so.
$i++;
}
// Selecting the width of rectangle
// so that difference between any
// two number is 1 only. Here width
// is selected so now flag is again
// unset for next rectangle
else if (($a[$i] == $a[$i + 1] or
$a[$i] - $a[$i + 1] == 1) and
($flag))
{
// area is calculated for
// rectangle
$sum = $sum + $a[$i + 1] * $len;
// flag is set false
// for another rectangle
// which we can get from
1197
Chapter 214. Sum of Areas of Rectangles possible for an array
Output :
282
Source
https://www.geeksforgeeks.org/sum-area-rectangles-possible-array/
1198
Chapter 215
Input : n = 4
point1 = { -1, 5 }
point2 = { 1, 6 }
point3 = { 3, 5 }
point4 = { 2, 3 }
Output : 22
Distance of { 1, 6 }, { 3, 5 }, { 2, 3 } from
{ -1, 5 } are 3, 4, 5 respectively.
Therefore, sum = 3 + 4 + 5 = 12
Distance of { 3, 5 }, { 2, 3 } from { 1, 6 }
are 3, 4 respectively.
Therefore, sum = 12 + 3 + 4 = 19
Distance of { 2, 3 } from { 3, 5 } is 3.
Therefore, sum = 19 + 3 = 22.
1199
Chapter 215. Sum of Manhattan distances between all pairs of points
C++
Java
1200
Chapter 215. Sum of Manhattan distances between all pairs of points
class GFG {
// Return the sum of distance between all
// the pair of points.
static int distancesum(int x[], int y[], int n)
{
int sum = 0;
// for each point, finding distance to
// rest of the point
for (int i = 0; i < n; i++)
for (int j = i + 1; j < n; j++)
sum += (Math.abs(x[i] - x[j]) +
Math.abs(y[i] - y[j]));
return sum;
}
// Driven Program
public static void main(String[] args)
{
int x[] = { -1, 1, 3, 2 };
int y[] = { 5, 6, 5, 3 };
int n = x.length;
System.out.println(distancesum(x, y, n));
}
}
// This code is contributed by vt_m.
Python3
1201
Chapter 215. Sum of Manhattan distances between all pairs of points
return sum
# Driven Code
x = [ -1, 1, 3, 2 ]
y = [ 5, 6, 5, 3 ]
n = len(x)
print(distancesum(x, y, n) )
# This code is contributed by "Sharad_Bhardwaj".
C#
PHP
1202
Chapter 215. Sum of Manhattan distances between all pairs of points
<?php
// PHP Program to find sum
// of Manhattan distance
// between all the pairs
// of given points
// Return the sum of distance
// between all the pair of points.
function distancesum( $x, $y, $n)
{
$sum = 0;
// for each point, finding
// distance to rest of
// the point
for($i = 0; $i < $n; $i++)
for ($j = $i + 1; $j < $n; $j++)
$sum += (abs($x[$i] - $x[$j]) +
abs($y[$i] - $y[$j]));
return $sum;
}
// Driver Code
$x = array(-1, 1, 3, 2);
$y = array(5, 6, 5, 3);
$n = count($x);
echo distancesum($x, $y, $n);
// This code is contributed by anuj_67.
?>
Output:
22
1203
Chapter 215. Sum of Manhattan distances between all pairs of points
from xi to xk plus the distance between xj and xi . If there are A points smaller than xj
and S is the sum of distances from xi to smaller points, then the sum of distances from xj
to smaller points equals S + (xj – xi ) * A.
If we sort all points in non-decreasing order, we can easily compute the desired sum of
distances along one axis between each pair of coordinates in O(N) time, processing points
from left to right and using the above method.
Also, we don’t have to concern if two points are equal coordinates, after sorting points in
non-decreasing order, we say that a point xi is smaller xj if and only if it appears earlier in
the sorted array.
Below is the implementation of this approach:
C++
1204
Chapter 215. Sum of Manhattan distances between all pairs of points
return 0;
}
Java
1205
Chapter 215. Sum of Manhattan distances between all pairs of points
}
// This code is contributed by vt_m.
Python3
C#
1206
Chapter 215. Sum of Manhattan distances between all pairs of points
PHP
<?php
// PHP Program to find sum of
// Manhattan distances between
// all the pairs of given points
// Return the sum of
// distance of one axis.
function distancesum($arr, $n)
1207
Chapter 215. Sum of Manhattan distances between all pairs of points
{
// sorting the array.
sort($arr);
// for each point,
// finding the distance.
$res = 0; $sum = 0;
for ($i = 0; $i < $n; $i++)
{
$res += ($arr[$i] * $i - $sum);
$sum += $arr[$i];
}
return $res;
}
function totaldistancesum($x, $y, $n)
{
return distancesum($x, $n) +
distancesum($y, $n);
}
// Driver Code
$x = array(-1, 1, 3, 2);
$y = array(5, 6, 5, 3);
$n = sizeof($x);
echo totaldistancesum($x, $y, $n), "\n";
// This code is contributed by m_kit
?>
Output :
22
Source
https://www.geeksforgeeks.org/sum-manhattan-distances-pairs-points/
1208
Chapter 216
As shown in the figure below, and show upper and lower tangent respec-
tively.
Examples:
Input : First Polygon : {(2, 2), (3, 3), (5, 2), (4, 0), (3, 1)}
Second Polygon : {(-1, 0), (0, 1), (1, 0), (0, -2)}.
Output : Upper Tangent - line joining (0,1) and (3,3)
Lower Tangent - line joining (0,-2) and (4,0)
Overview:
1209
Chapter 216. Tangents between two Convex Polygons
For finding the upper tangent, we start by taking two points. The rightmost point of a and
leftmost point of b. The line joining them is labelled as 1. As this line passes through the
polygon b (is not above polygon b) so we take the anti-clockwise next point on b, the line
is labelled 2. Now the line is above the polygon b, fine! But the line is crossing the polygon
a, so we move to the clockwise next point, labelled as 3 in the picture. This again crossing
the polygon a so we move to line 4. This line is crossing b so we move to line 5. Now this
line is crossing neither of the points. So this is the upper tangent for the given polygons.
For finding the lower tangent we need to move inversely through the polygons i.e. if the line
is crossing the polygon b we move to clockwise next and to anti-clockwise next if the line is
crossing the polygon a.
Algorithm for upper tangent:
L
Algorithm for lower tangent:
L
// C++ program to find upper tangent of two polygons.
#include<bits/stdc++.h>
using namespace std;
// stores the center of polygon (It is made
// global becuase it is used in compare function)
pair<int,int> mid;
// determines the quadrant of a point
// (used in compare())
int quad(pair<int,int> p)
{
if (p.first >= 0 && p.second >= 0)
return 1;
if (p.first <= 0 && p.second >= 0)
return 2;
if (p.first <= 0 && p.second <= 0)
1210
Chapter 216. Tangents between two Convex Polygons
return 3;
return 4;
}
// Checks whether the line is crossing the polygon
int orientation(pair<int,int> a, pair<int,int> b,
pair<int,int> c)
{
int res = (b.second-a.second)*(c.first-b.first) -
(c.second-b.second)*(b.first-a.first);
if (res == 0)
return 0;
if (res > 0)
return 1;
return -1;
}
// compare function for sorting
bool compare(pair<int,int> p1, pair<int,int> q1)
{
pair<int,int> p = make_pair(p1.first - mid.first,
p1.second - mid.second);
pair<int,int> q = make_pair(q1.first - mid.first,
q1.second - mid.second);
int one = quad(p);
int two = quad(q);
if (one != two)
return (one < two);
return (p.second*q.first < q.second*p.first);
}
// Finds upper tangent of two polygons 'a' and 'b'
// represented as two vectors.
void findUpperTangent(vector<pair<int,int> > a,
vector<pair<int,int> > b)
{
// n1 -> number of points in polygon a
// n2 -> number of points in polygon b
int n1 = a.size(), n2 = b.size();
// To find a point inside the convex polygon(centroid),
// we sum up all the coordinates and then divide by
// n(number of points). But this would be a floating-point
// value. So to get rid of this we multiply points
// initially with n1 and then find the centre and
1211
Chapter 216. Tangents between two Convex Polygons
1212
Chapter 216. Tangents between two Convex Polygons
1213
Chapter 216. Tangents between two Convex Polygons
a.push_back({5, 2});
a.push_back({4, 0});
vector<pair<int,int> > b;
b.push_back({0, 1});
b.push_back({1, 0});
b.push_back({0, -2});
b.push_back({-1, 0});
findUpperTangent(a, b);
return 0;
}
Output:
Note that the above code only finds upper tangent. We can similarly find lower tangent.
Source
https://www.geeksforgeeks.org/tangents-two-convex-polygons/
1214
Chapter 217
Tetradecagonal number
Input : 5
Output :125
Input :7
Output :259
1215
Chapter 217. Tetradecagonal number
C++
Java
1216
Chapter 217. Tetradecagonal number
Python 3
1217
Chapter 217. Tetradecagonal number
"number : " ,
tetradecagonal_num(n))
# This code is contributed ajit
C#
PHP
<?php
// Program to find nth
// Tetradecagonal number
1218
Chapter 217. Tetradecagonal number
// Function to find
// Tetradecagonal number
function tetradecagonal_num($n)
{
// Formula to calculate nth
// tetradecagonal number=
return (12 * $n * $n - 10 * $n) / 2;
}
// Driver Code
$n = 2;
echo $n , " th Tetradecagonal number: ";
echo tetradecagonal_num($n), "\n";
$n = 6;
echo $n ," th Tetradecagonal number: ";
echo tetradecagonal_num($n);
// This code is contributed by aj_36
?>
Output :
2 th Tetradecagonal number: 14
6 th Tetradecagonal number: 186
Reference:
https://en.wikipedia.org/wiki/Polygonal_number
Improved By : jit_t
Source
https://www.geeksforgeeks.org/tetradecagonal-number/
1219
Chapter 218
Examples:
1220
Chapter 218. Total area of two overlapping rectangles
Asked in Juniper
We basically add areas of two rectangles. This includes intersecting part twice, so we subtract
area of intersecting part.
1221
Chapter 218. Total area of two overlapping rectangles
abs(l2.y - r2.y);
// Length of intersecting part i.e
// start from max(l1.x, l2.x) of
// x-coordinate and end at min(r1.x,
// r2.x) x-coordinate by subtracting
// start from end we get required
// lengths
int areaI = (min(r1.x, r2.x) -
max(l1.x, l2.x)) *
(min(r1.y, r2.y) -
max(l1.y, l2.y));
return (area1 + area2 - areaI);
}
// Driver's Code
int main()
{
Point l1 = { 2, 2 }, r1 = { 5, 7 };
Point l2 = { 3, 4 }, r2 = { 6, 9 };
cout << overlappingArea(l1, r1, l2, r2);
return 0;
}
Output:
24
Source
https://www.geeksforgeeks.org/total-area-two-overlapping-rectangles/
1222
Chapter 219
The solution is based on the fact that if there exist triangle(s) with no points inside, then
we can form a triangle with any random point among all points.
We can solve this problem by searching all three points one by one. The first point can
be chosen randomly. After choosing the first point, we need two points such that their
slope should be different and no point should lie inside the triangle of these three points.
We can do this by choosing the second point as nearest point to the first and third point
as second nearest point with the different slope. For doing this, we first iterate over
all points and choose the point which is nearest to the first one and designate that as
second point of the required triangle. Then we iterate one more time to find point which
has different slope and has the smallest distance, which will be the third point of our triangle.
C++
1223
Chapter 219. Triangle with no point inside
1224
Chapter 219. Triangle with no point inside
Java
1225
Chapter 219. Triangle with no point inside
1226
Chapter 219. Triangle with no point inside
Output:
0, 0
1, 1
0, 2
1227
Chapter 219. Triangle with no point inside
Source
https://www.geeksforgeeks.org/triangle-no-point-inside/
1228
Chapter 220
Input : X = 1
Output : 3
Input : X = 2
Output : 9
This is mainly an extension of triangular numbers. For a number X, the matchstick required
will be three times of X-th triangular numbers, i.e., (3*X*(X+1))/2
1229
Chapter 220. Triangular Matchstick Number
C++
Java
1230
Chapter 220. Triangular Matchstick Number
return (3 * x * (x + 1)) / 2;
}
public static void main(String[] args)
{
System.out.println(numberOfSticks(7));
}
}
Python3
C#
PHP
<?php
// PHP program to find
// X-th triangular
1231
Chapter 220. Triangular Matchstick Number
// matchstick number
function numberOfSticks($x)
{
return (3 * $x * ($x + 1)) / 2;
}
// Driver code
echo(numberOfSticks(7));
// This code is contributed by Ajit.
?>
Output:
84
Improved By : jit_t
Source
https://www.geeksforgeeks.org/triangular-matchstick-number/
1232
Chapter 221
Ways to choose three points with distance between the most distant points <= L - Geeks-
forGeeks
Given a set of n distinct points x1 , x2 , x3 … xn all lying on the X-axis and an integer L, the
task is to find the number of ways of selecting three points such that the distance between
the most distant points is less than or equal to L
Note: Order is not important i.e the points {3, 2, 1} and {1, 2, 3} represent the same set
of three points
Examples:
Input : x = {1, 2, 3, 4}
L=3
Output : 4
Explanation:
Ways to select three points such that the distance between
the most distant points <= L are:
1) {1, 2, 3} Here distance between farthest points = 3 – 1 = 2 <= L
2) {1, 2, 4} Here distance between farthest points = 4 – 1 = 3 <= L
3) {1, 3, 4} Here distance between farthest points = 4 – 1 = 3 <= L
4) {2, 3, 4} Here distance between farthest points = 4 – 2 = 2 <= L
Thus, total number of ways = 4
Naive Approach:
First of all, sort the array of points to generate triplets {a, b, c} such that a and c are
the farthest points of the triplet and a < b < c, since all the points are distinct. We can
1233
Chapter 221. Ways to choose three points with distance between the most distant points
<= L
generate all the possible triplets and check for the condition if the distance between the
two most distant points in <= L. If it holds we count this way, else we don’t
C++
1234
Chapter 221. Ways to choose three points with distance between the most distant points
<= L
Java
1235
Chapter 221. Ways to choose three points with distance between the most distant points
<= L
return ways;
}
// Driver Code
static public void main (String[] args)
{
// set of n points on the X axis
int []arr = {1, 2, 3, 4};
int n =arr.length;
int L = 3;
int ans = countTripletsLessThanL(n, L, arr);
System.out.println("Total Number of ways = "
+ ans);
}
}
// This code is contributed by anuj_67.
C#
1236
Chapter 221. Ways to choose three points with distance between the most distant points
<= L
// Since the array is sorted the
// farthest points will be a[i]
// and a[k];
int mostDistantDistance = arr[k] - arr[i];
if (mostDistantDistance <= L)
{
ways++;
}
}
}
}
return ways;
}
// Driver Code
static public void Main ()
{
// set of n points on the X axis
int []arr = {1, 2, 3, 4};
int n =arr.Length;
int L = 3;
int ans = countTripletsLessThanL(n, L, arr);
Console.WriteLine("Total Number of ways = " + ans);
}
}
// This code is contributed by anuj_67.
Output
1237
Chapter 221. Ways to choose three points with distance between the most distant points
<= L
• Doing so we find all such points where the distance between the farthest points will
always be less than or equal to L.
• Now let’s say for the ith point, we have M such points which are less than or equal to
xi + L, then the number of ways we can select 2 points from M such points is simply
M * (M – 1) / 2
1238
Chapter 221. Ways to choose three points with distance between the most distant points
<= L
// Driver Code
int main()
{
// set of n points on the X axis
int arr[] = { 1, 2, 3, 4 };
int n = sizeof(arr) / sizeof(arr[0]);
int L = 4;
int ans = countTripletsLessThanL(n, L, arr);
cout << "Total Number of ways = " << ans << "\n";
return 0;
}
Output
Source
https://www.geeksforgeeks.org/ways-choose-three-points-distance-distant-points-l/
1239
Chapter 222
Input: n = 1
Output: 1
Input: n = 2
Output: 5
Input: n = 3
Output: 12
If we put s = 5, we get
1240
Chapter 222. n’th Pentagonal Number
Examples:
Pentagonal Number
Java
1241
Chapter 222. n’th Pentagonal Number
{
return (3*n*n - n)/2;
}
}
public class GeeksCode
{
public static void main(String[] args)
{
Pentagonal obj = new Pentagonal();
int n = 10;
System.out.printf("10th petagonal number is = "
+ obj.pentagonalNum(n));
}
}
Python
C#
1242
Chapter 222. n’th Pentagonal Number
}
// This code is contributed by vt_m.
PHP
<?php
// PHP program for above approach
// Finding the nth Pentagonal Number
function pentagonalNum($n)
{
return (3 * $n * $n - $n) / 2;
}
// Driver Code
$n = 10;
echo "10th Pentagonal Number is = ",
pentagonalNum($n);
// This code is contributed by ajit
?>
Output :
Reference:
https://en.wikipedia.org/wiki/Polygonal_number
Improved By : jit_t
Source
https://www.geeksforgeeks.org/nth-pentagonal-number/
1243