📌  相关文章
📜  将N ^ 2个数分成相等数目的N组

📅  最后修改于: 2021-06-25 22:44:59             🧑  作者: Mango

给定一个偶数N。任务是考虑从1到N 2的数字,将它们分成相等数目的N个组。
例子

Input: N = 2
Output: {1, 4}, {2, 3}
Two groups of equal sum are 1, 4 and 2,3

Input: N = 4
Output: 
{ 1, 16} { 2, 15} 
{ 3, 14} { 4, 13} 
{ 5, 12} { 6, 11} 
{ 7, 10} { 8, 9}

方法:前N 2个数字之和的公式: Sum =(N 2 *(N 2 +1))/ 2
因此,每个组的总和将是=(N 2 + 1)* N 2/2
让我们考虑以下类型的对(1,N 2 ),(2,N 2 -1),依此类推。
由于N 2是偶数,所以可以使用正好N / 2个这样的对来构成每个组。
下面是上述方法的实现:

C++
// C++ implementation of the above approach
#include 
using namespace std;
 
// Function to print N groups of equal sum
void printGroups(int n)
{
    int x = 1;
    int y = n * n;
 
    // No. of Groups
    for (int i = 1; i <= n; i++) {
 
        // n/2 pairs
        for (int j = 1; j <= n / 2; j++) {
            cout << "{ " << x << ", " << y << "} ";
            x++;
            y--;
        }
 
        cout << endl;
    }
}
 
// Driver code
int main()
{
    int n = 4;
    printGroups(n);
 
    return 0;
}


Java
// Java implementation of the above approach
 
import java.io.*;
 
class GFG {
     
 
 
// Function to print N groups of equal sum
static void printGroups(int n)
{
    int x = 1;
    int y = n * n;
 
    // No. of Groups
    for (int i = 1; i <= n; i++) {
 
        // n/2 pairs
        for (int j = 1; j <= n / 2; j++) {
            System.out.print("{ " + x + ", " + y + "} ");
            x++;
            y--;
        }
 
        System.out.println();
    }
}
 
// Driver code
 
    public static void main (String[] args) {
            int n = 4;
    printGroups(n);
    }
}
// This code is contributed by shs


Python3
# Python implementation of the above approach
 
# Function to print N groups of equal sum
def printGroups(n) :
     
    x = 1
    y = n * n
     
    # No. of Groups
    for i in range(1, n + 1) :
         
        # n/2 pairs
        for j in range(1, n // 2 + 1) :
             
            print("{",x,",",y,"}",end = " ")
             
            x += 1
            y -= 1
         
        print()
         
        
# Driver code
if __name__ == "__main__" :
     
    n = 4
     
    # Function call
    printGroups(n)
 
# This code is contributed by Ryuga


C#
// Java implementation of the
// above approach
using System;
 
class GFG
{
     
// Function to print N groups
// of equal sum
static void printGroups(int n)
{
    int x = 1;
    int y = n * n;
 
    // No. of Groups
    for (int i = 1; i <= n; i++)
    {
 
        // n/2 pairs
        for (int j = 1; j <= n / 2; j++)
        {
            Console.Write("{ " + x + ", " + y + "} ");
            x++;
            y--;
        }
 
        Console.WriteLine();
    }
}
 
// Driver code
public static void Main ()
{
    int n = 4;
    printGroups(n);
}
}
 
// This code is contributed by shs


PHP


Javascript


输出:
{ 1, 16} { 2, 15} 
{ 3, 14} { 4, 13} 
{ 5, 12} { 6, 11} 
{ 7, 10} { 8, 9}

如果您希望与行业专家一起参加现场课程,请参阅《 Geeks现场课程》和《 Geeks现场课程美国》。