📜  计算给定范围内可能的成对对

📅  最后修改于: 2021-04-17 18:48:00             🧑  作者: Mango

给定两个正整数LR (其中L≤R ),任务是计算可以通过添加范围[L,R]中的任意一对整数而获得的不同整数的数量。

例子:

天真的方法:解决给定问题的最简单方法是从[L,R]范围中找到所有可能的数字对的总和,并打印获得的所有不同总和的计数。

时间复杂度: O((L – R) 2 )
辅助空间: O(1)

高效的方法:可以基于以下观察来优化上述方法:

  • 由于给定的范围[L,R]是连续的,因此通过加法获得的数字范围也将是连续的。
  • 该范围内的对的最小和最大总和分别由2 * L2 * R给出
  • 因此,对的计数不同总和由(2 * R – 2 * L +1)给出

下面是上述方法的实现:

C++
// C++ program for the above approach
#include 
using namespace std;
 
// Function to count distinct sum of
// pairs possible from the range [L, R]
int distIntegers(int L, int R)
{
    // Return the count of
    // distinct sum of pairs
    return 2 * R - 2 * L + 1;
}
 
// Driver Code
int main()
{
    int L = 3, R = 8;
    cout << distIntegers(L, R);
 
    return 0;
}


Java
// Java program for the above approach
import java.io.*;
 
class GFG{
     
// Function to count distinct sum of
// pairs possible from the range [L, R]
static int distIntegers(int L, int R)
{
     
    // Return the count of
    // distinct sum of pairs
    return 2 * R - 2 * L + 1;
}
  
// Driver Code
public static void main (String[] args)
{
    int L = 3, R = 8;
     
    System.out.println(distIntegers(L, R));
}
}
 
// This code is contributed by rag2127


Python3
# Python3 program for the above approach
 
# Function to count distinct sum of
# pairs possible from the range [L, R]
def distIntegers(L, R):
   
    # Return the count of
    # distinct sum of pairs
    return 2 * R - 2 * L + 1
 
# Driver Code
if __name__ == '__main__':
    L, R = 3, 8
    print (distIntegers(L, R))
 
# This code is contributed by mohit kumar 29.


C#
// C# program for the above approach
using System;
using System.Collections.Generic;
 
class GFG{
     
// Function to count distinct sum of
// pairs possible from the range [L, R]
static int distIntegers(int L, int R)
{
     
    // Return the count of
    // distinct sum of pairs
    return 2 * R - 2 * L + 1;
}
 
// Driver Code
static public void Main()
{
    int L = 3, R = 8;
     
    Console.Write(distIntegers(L, R));
}
}
 
// This code is contributed by avijitmondal1998


Javascript


输出:
11

时间复杂度: O(1)
辅助空间: O(1)