这里给出了n 个倾斜的正方形,它们的顶点在外部相互接触,并排成一排。第一个正方形和最后一个正方形的中心之间的距离是给定的。正方形的边长相等。任务是找到每个正方形的边。
例子:
Input :d = 42, n = 4
Output :The side of each square is 9.899
Input :d = 54, n = 7
Output :The side of each square is 6.364
方法:
有 n 个正方形,每个正方形的边长为 a,第一个正方形和最后一个正方形之间的距离等于 d。从图中可以看出,它们之间是由对角线连接的。每条对角线的长度等于a√2 。
对于第一个和最后一个正方形,只有一半的对角线被长度 d 覆盖。对于其余的 (n-2) 个正方形,完整的对角线被 d 覆盖。因此 a 和 d 之间的关系如下:
a/√2 + a/√2 + (n-2)*a√2 = d
=> a√2 + √2na – 2a√2 = d
=> n√2a – a√2 = d
=> a = d/((n-1)*(√2))
Side of the square = distance between centers/((no. of squares-1) * sqrt(2)).
下面是上述方法的实现:
C++
// C++ program to find side of the squares
// inclined and touch each other externally
// at vertices and are lined in a row
// and distance between the
// centers of first and last squares is given
#include
using namespace std;
void radius(double n, double d)
{
cout << "The side of each square is "
<< d / ((n - 1) * sqrt(2)) << endl;
}
// Driver code
int main()
{
double d = 42, n = 4;
radius(n, d);
return 0;
}
Java
// Java program to find side of the squares
// inclined and touch each other externally
// at vertices and are lined in a row
// and distance between the
// centers of first and last squares is given
import java.io.*;
class GFG
{
static void radius(double n, double d)
{
System.out.print( "The side of each square is "+
d / ((n - 1) * Math.sqrt(2)));
}
// Driver code
public static void main (String[] args)
{
double d = 42, n = 4;
radius(n, d);
}
}
// This code is contributed by anuj_67..
Python3
# Python program to find side of the squares
# inclined and touch each other externally
# at vertices and are lined in a row
# and distance between the
# centers of first and last squares is given
def radius(n, d):
print("The side of each square is ",
d / ((n - 1) * (2**(1/2))));
# Driver code
d = 42; n = 4;
radius(n, d);
# This code is contributed by Rajput-Ji
C#
// C# program to find side of the squares
// inclined and touch each other externally
// at vertices and are lined in a row
// and distance between the
// centers of first and last squares is given
using System;
class GFG
{
static void radius(double n, double d)
{
Console.WriteLine( "The side of each square is "+
d / ((n - 1) * Math.Sqrt(2)));
}
// Driver code
public static void Main ()
{
double d = 42, n = 4;
radius(n, d);
}
}
// This code is contributed by anuj_67..
Javascript
输出:
The side of each square is 9.89949
时间复杂度: O(1)
如果您希望与专家一起参加现场课程,请参阅DSA 现场工作专业课程和学生竞争性编程现场课程。