📌  相关文章
📜  从数字1到N形成的递减对的计数

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

给定整数N ,任务是计算从数字1到N的递减对。

例子:

方法:考虑以下情况:

可以清楚地观察到
\text{Count of Decreasing pairs = }\begin{cases} \frac{N}{2} & \text{, if N is odd}\\ \frac{N}{2}-1 & \text{, if N is even} \end{cases}
下面是上述方法的实现:

C++
// C++ program to count decreasing
// pairs formed from numbers 1 to N
 
#include 
using namespace std;
 
// Function to count the
// possible number of pairs
int divParts(int N)
{
    if (N % 2 == 0)
 
        // if the number is even
        // then the answer in (N/2)-1
        cout << (N / 2) - 1 << endl;
 
    else
        // if the number is odd
        // then the answer in N/2
        cout << N / 2 << endl;
}
 
// Driver code
int main()
{
    int N = 8;
 
    divParts(N);
 
    return 0;
}


Java
// Java program to count decreasing
// pairs formed from numbers 1 to N
import java.util.*;
class GFG{
     
// Function to count the
// possible number of pairs
static void divParts(int N)
{
    if (N % 2 == 0)
 
        // if the number is even
        // then the answer in (N/2)-1
        System.out.println((N / 2) - 1);
 
    else
        // if the number is odd
        // then the answer in N/2
        System.out.println((N / 2));
}
 
// Driver code
public static void main(String[] args)
{
    int N = 8;
 
    divParts(N);
}
}
 
// This code is contributed by offbeat


Python3
# Python3 program to count decreasing
# pairs formed from numbers 1 to N
 
# Function to count the
# possible number of pairs
def divParts(N):
 
    if (N % 2 == 0):
 
        # if the number is even
        # then the answer in (N/2)-1
        print((N / 2) - 1);
 
    else:
         
        # if the number is odd
        # then the answer in N/2
        print(N / 2);
 
# Driver code
N = 8;
divParts(N);
 
# This code is contributed by Code_Mech


C#
// C# program to count decreasing
// pairs formed from numbers 1 to N
using System;
class GFG{
     
// Function to count the
// possible number of pairs
static void divParts(int N)
{
    if (N % 2 == 0)
 
        // if the number is even
        // then the answer in (N/2)-1
        Console.WriteLine((N / 2) - 1);
 
    else
        // if the number is odd
        // then the answer in N/2
        Console.WriteLine((N / 2));
}
 
// Driver code
public static void Main()
{
    int N = 8;
 
    divParts(N);
}
}
 
// This code is contributed by Code_Mech


Javascript


输出:
3