给定数字N表示矩阵中元素的总数,任务是打印矩阵的所有可能顺序。顺序是一对(m,n)整数,其中m是行数,n是列数。例如,如果元素数为8,则所有可能的顺序为:
(1、8),(2、4),(4、2),(8、1)。
例子:
Input: N = 8
Output: (1, 2) (2, 4) (4, 2) (8, 1)
Input: N = 100
Output:
(1, 100) (2, 50) (4, 25) (5, 20) (10, 10) (20, 5) (25, 4) (50, 2) (100, 1)
方法:
如果矩阵具有m行和n列,则称其为mxn阶。矩阵中元素的总数等于(m * n)。因此,我们从1开始并逐一检查是否除以N(元素总数)。如果它分裂,它将是一种可能的顺序。
下面是上述方法的实现:
C++
// C++ implementation of the above approach
#include
using namespace std;
// Function to print all possible order
void printAllOrder(int n)
{
// total number of elements in a matrix
// of order m * n is equal (m*n)
// where m is number of rows and n is
// number of columns
for (int i = 1; i <= n; i++) {
// if n is divisible by i then i
// and n/i will be the one
// possible order of the matrix
if (n % i == 0) {
// print the given format
cout << i << " " << n / i << endl;
}
}
}
// Driver code
int main()
{
int n = 10;
printAllOrder(n);
return 0;
}
Java
// Java implementation of the above approach
class GFG
{
// Function to print all possible order
static void printAllOrder(int n)
{
// total number of elements in a matrix
// of order m * n is equal (m*n)
// where m is number of rows and n is
// number of columns
for (int i = 1; i <= n; i++) {
// if n is divisible by i then i
// and n/i will be the one
// possible order of the matrix
if (n % i == 0) {
// print the given format
System.out.println( i + " " + n / i );
}
}
}
// Driver code
public static void main(String []args)
{
int n = 10;
printAllOrder(n);
}
}
// This code is contributed by ihritik
Python
# Python implementation of the above approach
# Function to print all possible order
def printAllOrder(n):
# total number of elements in a matrix
# of order m * n is equal (m*n)
# where m is number of rows and n is
# number of columns
for i in range(1,n+1):
# if n is divisible by i then i
# and n/i will be the one
# possible order of the matrix
if (n % i == 0) :
# print the given format
print( i ,n // i )
# Driver code
n = 10
printAllOrder(n)
# This code is contributed by ihritik
C#
// C# implementation of the above approach
using System;
class GFG
{
// Function to print all possible order
static void printAllOrder(int n)
{
// total number of elements in a matrix
// of order m * n is equal (m*n)
// where m is number of rows and n is
// number of columns
for (int i = 1; i <= n; i++) {
// if n is divisible by i then i
// and n/i will be the one
// possible order of the matrix
if (n % i == 0) {
// print the given format
Console.WriteLine( i + " " + n / i );
}
}
}
// Driver code
public static void Main()
{
int n = 10;
printAllOrder(n);
}
}
// This code is contributed by ihritik
PHP
Javascript
输出:
1 10
2 5
5 2
10 1
时间复杂度: O(n)
辅助空间: O(1)