给定大小为A x B的纸张。任务是将纸张切成任意大小的正方形。找到可以从纸上切出的最小平方数。
例子:
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)
我们知道,如果要从纸上裁切最小的正方形,则必须首先从纸上裁切最大的正方形,并且最大的裁切面与纸的较小面相同。例如,如果纸张尺寸为13 x 29,则最大正方形将在面13处。因此,我们可以裁切2个尺寸为13 x 13的正方形(29/13 = 2)。现在剩余的纸张将具有3 x 13的尺寸。类似地,我们可以通过使用4个3 x 3的正方形和3个1 x 1的正方形来裁切剩余的纸张。因此,可以从13 x 29的Paper中裁切最少9个正方形。
下面是上述方法的实现。
C++
// C++ program to find minimum number of squares
// to cut a paper.
#include
using namespace std;
// Returns min number of squares needed
int minimumSquare(int a, int b)
{
long long result = 0, rem = 0;
// swap if a is small size side .
if (a < b)
swap(a, b);
// Iterate until small size side is
// greater then 0
while (b > 0)
{
// Update result
result += a/b;
long long rem = a % b;
a = b;
b = rem;
}
return result;
}
// Driver code
int main()
{
int n = 13, m = 29;
cout << minimumSquare(n, m);
return 0;
}
Java
// Java program to find minimum
// number of squares to cut a paper.
class GFG{
// To swap two numbers
static void swap(int a,int b)
{
int temp = a;
a = b;
b = temp;
}
// Returns min number of squares needed
static int minimumSquare(int a, int b)
{
int result = 0, rem = 0;
// swap if a is small size side .
if (a < b)
swap(a, b);
// Iterate until small size side is
// greater then 0
while (b > 0)
{
// Update result
result += a/b;
rem = a % b;
a = b;
b = rem;
}
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
# Python 3 program to find minimum
# number of squares to cut a paper.
# Returns min number of squares needed
def minimumSquare(a, b):
result = 0
rem = 0
# swap if a is small size side .
if (a < b):
a, b = b, a
# Iterate until small size side is
# greater then 0
while (b > 0):
# Update result
result += int(a / b)
rem = int(a % b)
a = b
b = rem
return result
# Driver code
n = 13
m = 29
print(minimumSquare(n, m))
# This code is contributed by
# Smitha Dinesh Semwal
C#
// C# program to find minimum
// number of squares to cut a paper.
using System;
class GFG
{
// To swap two numbers
static void swap(int a, int b)
{
int temp = a;
a = b;
b = temp;
}
// Returns min number of squares needed
static int minimumSquare(int a, int b)
{
int result = 0, rem = 0;
// swap if a is small size side .
if (a < b)
swap(a, b);
// Iterate until small size side is
// greater then 0
while (b > 0)
{
// Update result
result += a / b;
rem = a % b;
a = b;
b = rem;
}
return result;
}
// Driver code
public static void Main(String[] args)
{
int n = 13, m = 29;
Console.WriteLine(minimumSquare(n, m));
}
}
// This code is contributed by 29AjayKumar
输出:
9
请注意,上述贪婪解决方案并不总是能产生最佳结果。例如,如果输入为36 x 30,则上述算法将产生输出6,但是我们可以将纸张切成5个正方形
1)三个大小为12 x 12的正方形
2)大小为18 x 18的两个正方形。
感谢Sergey V. Pereslavtsev指出了上述情况。