📌  相关文章
📜  从1到n的数字最近的和分区(分为两个子集)

📅  最后修改于: 2021-04-23 19:01:50             🧑  作者: Mango

给定整数序列1,2,3,4,…,n 。任务是将其划分为两个集合AB ,使得每个元素恰好属于一个集合,并且| sum(A)– sum(B)|是最小的。打印| sum(A)– sum(B)|的值

例子:

方法:mod = n%4

  1. 如果mod = 0mod = 3,则打印0
  2. 如果mod = 1mod = 2,则打印1

这是因为将选择以下组:A = {N,N – 3,N – 4,N – 7,N – 8,…..},B = {N – 1,N – 2,N – 5 N – 6,…..}
从N到1,在组A中放置第一个元素,然后在B,A,B,A,…..中每隔两个元素交替。

  • n%4 = 0时: N = 8,A = {1,4,5,8}和B = {2,3,6,7}
  • n%4 = 1时: N = 9,A = {1、4、5、8、9},B = {2、3、6、7}
  • n%4 = 2时: N = 10,则A = {1、4、5、8、9},而B = {2、3、6、7、10}
  • n%4 = 3时: N = 11,A = {1、4、5、8、9},B = {2、3、6、7、10、11}

下面是上述方法的实现:

C++
// C++ implementation of the approach
#include 
using namespace std;
  
// Function to return the minimum required
// absolute difference
int minAbsDiff(int n)
{
    int mod = n % 4;
  
    if (mod == 0 || mod == 3)
        return 0;
  
    return 1;
}
  
// Driver code
int main()
{
    int n = 5;
    cout << minAbsDiff(n);
  
    return 0;
}


Java
// Java implementation of the approach
class GFG 
{
      
// Function to return the minimum required 
// absolute difference 
  
    static int minAbsDiff(int n)
    {
        int mod = n % 4;
        if (mod == 0 || mod == 3) 
        {
            return 0;
        }
        return 1;
    }
  
    // Driver code 
    public static void main(String[] args) 
    {
        int n = 5;
        System.out.println(minAbsDiff(n));
    }
}
  
// This code is contributed by Rajput-JI


Python 3
# Python3 implementation of the approach 
  
# Function to return the minimum required 
# absolute difference 
def minAbsDiff(n) :
    mod = n % 4; 
  
    if (mod == 0 or mod == 3) :
        return 0; 
  
    return 1; 
  
# Driver code 
if __name__ == "__main__" :
  
    n = 5; 
    print(minAbsDiff(n)) 
      
# This code is contributed by Ryuga


C#
// C# implementation of the 
// above approach
using System;
  
class GFG
{
          
    // Function to return the minimum  
    // required absolute difference 
    static int minAbsDiff(int n)
    {
        int mod = n % 4;
        if (mod == 0 || mod == 3) 
        {
            return 0;
        }
        return 1;
    }
  
    // Driver code 
    static public void Main ()
    {
        int n = 5;
        Console.WriteLine(minAbsDiff(n));
    }
}
  
// This code is contributed by akt_mit


PHP


输出:
1