给定周长可能的最大不同矩形计数
给定一个整数N表示矩形的周长。任务是找出给定周长可能存在的不同矩形的数量。
例子
Input: N = 10
Output: 4
Explanation: All the rectangles with perimeter 10 are following in the form of (length, breadth):
(1, 4), (4, 1), (2, 3), (3, 2)
Input: N = 8
Output: 3
方法:这个问题可以通过使用矩形的属性来解决。请按照以下步骤解决给定的问题。
- 矩形的周长是2*(length + width) 。
- 如果N是奇数,则不可能有矩形。因为周长永远不会是奇数。
- 如果N小于4 ,那么也不可能存在任何矩形。由于边的最小可能长度为1 ,因此即使所有边的长度为1 ,那么周长也是4 。
- 现在N = 2*(l + b)和(l + b) = N/2 。
- 因此,需要找到总和为N/2的所有对,即(N/2) – 1 。
下面是上述方法的实现。
C++
#include
using namespace std;
// Function to find the maximum number
// of distinct rectangles with given perimeter
void maxRectanglesPossible(int N)
{
// Invalid case
if (N < 4 || N % 2 != 0) {
cout << -1 << "\n";
}
else
// Number of distinct rectangles.
cout << (N / 2) - 1 << "\n";
}
// Driver Code
int main()
{
// Perimeter of the rectangle.
int N = 20;
maxRectanglesPossible(N);
return 0;
}
Java
// Java program for the above approach
import java.io.*;
import java.lang.*;
import java.util.*;
class GFG {
// Function to find the maximum number
// of distinct rectangles with given perimeter
static void maxRectanglesPossible(int N)
{
// Invalid case
if (N < 4 || N % 2 != 0) {
System.out.println(-1);
}
else
// Number of distinct rectangles.
System.out.println((N / 2) - 1);
}
// Driver Code
public static void main (String[] args) {
// Perimeter of the rectangle.
int N = 20;
maxRectanglesPossible(N);
}
}
// This code is contributed by hrithikgarg0388.
Python3
# Function to find the maximum number
# of distinct rectangles with given perimeter
def maxRectanglesPossible (N):
# Invalid case
if (N < 4 or N % 2 != 0):
print("-1");
else:
# Number of distinct rectangles.
print(int((N / 2) - 1));
# Driver Code
# Perimeter of the rectangle.
N = 20;
maxRectanglesPossible(N);
# This code is contributed by gfgking
C#
// C# program for the above approach
using System;
class GFG {
// Function to find the maximum number
// of distinct rectangles with given perimeter
static void maxRectanglesPossible(int N)
{
// Invalid case
if (N < 4 || N % 2 != 0) {
Console.WriteLine(-1);
}
else
// Number of distinct rectangles.
Console.WriteLine((N / 2) - 1);
}
// Driver Code
public static void Main () {
// Perimeter of the rectangle.
int N = 20;
maxRectanglesPossible(N);
}
}
// This code is contributed by Samim Hossain Mondal.
Javascript
输出
9
时间复杂度: O(1)
辅助空间: O(1)