给定两个正整数L和R (其中L ≤ R ),任务是计算通过将范围[L, R] 中的任意一对整数相加可以获得的不同整数的数量。
例子:
Input: L = 3, R = 5
Output: 11
Explanation: All possible distinct sum of pairs are as follows:
- (3, 3). Sum = 6.
- (3, 4). Sum = 7.
- (3, 5). Sum = 8.
- (4, 5). Sum = 9.
- (5, 5). Sum = 10.
Therefore, the count of distinct sums is 5.
Input: L = 12, R = 14
Output: 5
朴素方法:解决给定问题的最简单方法是从范围[L, R] 中找到所有可能的数字对的总和,并打印获得的所有不同总和的计数。
时间复杂度: O((L – R) 2 )
辅助空间: O(1)
高效的方法:上述方法可以基于以下观察进行优化:
- 由于给定的范围[L, R]是连续的,因此通过相加得到的数字范围也将是连续的。
- 该范围内的最小和最大对总和分别由2 * L和2 * 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)