📌  相关文章
📜  计算将一个数字表示为正好两个数字之和的方式

📅  最后修改于: 2021-04-23 20:54:33             🧑  作者: Mango

给定正整数N。任务是找到将N表示为正好两个数字AB (N = A + B)之和的方式,其中A> 0,B> 0和B>A。

例子:

Input: N = 8
Output: 3
Explanation:
N = 8 can be expressed as (1, 7), (2, 6), (3, 5)

Input: N = 14
Output: 6

方法:

  • 此处的观察结果是,对于每个数字N,如果我们采用小于N / 2的数字A,那么必须存在大于N / 2的数字B且A + B =N。
  • 这导致找到B或A的数量计数的简单解决方案。因此,(N-1)/ 2的下限值将导致解决方案。
C++
// C++ program to Count ways to 
// express a number as sum of 
// two numbers.
#include 
using namespace std;
  
// Function returns the count 
// of ways express a number 
// as sum of two numbers.
int CountWays(int n)
{
    int ans = (n - 1) / 2;
      
    return ans;
}
  
// Driver code
int main()
{
   int N = 8;
     
    cout << CountWays(N);
}


Java
// Java program to count ways to 
// express a number as sum of 
// two numbers.
class GFG{
  
// Function returns the count 
// of ways express a number 
// as sum of two numbers.
static int CountWays(int n)
{
    int ans = (n - 1) / 2;
      
    return ans;
}
  
// Driver code
public static void main(String[] args)
{
    int N = 8;
    System.out.print(CountWays(N));
}
}
  
// This code is contributed by Rajput-Ji


Python3
# Python3 program to Count ways to 
# express a number as sum of 
# two numbers. 
  
# Function returns the count 
# of ways express a number 
# as sum of two numbers. 
def CountWays(n) :
    ans = (n - 1) // 2
    return ans
  
# Driver code 
N = 8
print(CountWays(N))
  
# This code is contributed by Sanjit_Prasad


C#
// C# program to count ways to 
// express a number as sum of 
// two numbers.
using System;
class GFG{
  
// Function returns the count 
// of ways express a number 
// as sum of two numbers.
static int CountWays(int n)
{
    int ans = (n - 1) / 2;
      
    return ans;
}
  
// Driver code
public static void Main()
{
    int N = 8;
    Console.Write(CountWays(N));
}
}
  
// This code is contributed by Code_Mech


输出:
3

时间复杂度: O(N)