给定四个整数a,b,c,d(最大为10 ^ 6)。任务是找到x 例子: 方法:让我们显式地迭代x的所有可能值。对于x的一个这样的固定值,问题减少到存在多少y值,使得c <= y <= d且x = max(c,x + 1)且y <= d 。假定c <= d ,否则,当然没有y的有效值。因此,对于固定的x,存在d – max(c,x + 1)+ 1个y的有效值,因为在[R1,R2]范围内的整数数目由R2 – R1 + 1给出。 下面是上述方法的实现:Input: a = 2, b = 3, c = 3, d = 4
Output: 3
Input: a = 3, b = 5, c = 6, d = 7
Output: 6
C++
// C++ implementation of above approach
#include
Java
// Java implementation of above approach
import java.io.*;
class GFG
{
// function to Find the number of
// solutions for x < y, where
// a <= x <= b and c <= y <= d
// and x, y integers.
static int NumberOfSolutions(int a, int b,
int c, int d)
{
// to store answer
int ans = 0;
// iterate explicitly over all
// possible values of x
for (int i = a; i <= b; i++)
if (d >= Math.max(c, i + 1))
ans += d - Math.max(c, i + 1) + 1;
// return answer
return ans;
}
// Driver code
public static void main (String[] args)
{
int a = 2, b = 3, c = 3, d = 4;
// function call
System.out.println(NumberOfSolutions(a, b, c, d));
}
}
// This code is contributed
// by inder_verma
Python 3
# Python3 implementation of
# above approach
# function to Find the number of
# solutions for x < y, where
# a <= x <= b and c <= y <= d and
# x, y integers.
def NumberOfSolutions(a, b, c, d) :
# to store answer
ans = 0
# iterate explicitly over all
# possible values of x
for i in range(a, b + 1) :
if d >= max(c, i + 1) :
ans += d - max(c, i + 1) + 1
# return answer
return ans
# Driver code
if __name__ == "__main__" :
a, b, c, d = 2, 3, 3, 4
# function call
print(NumberOfSolutions(a, b, c, d))
# This code is contributed by ANKITRAI1
C#
// C# implementation of above approach
using System;
class GFG
{
// function to Find the number of
// solutions for x < y, where
// a <= x <= b and c <= y <= d
// and x, y integers.
static int NumberOfSolutions(int a, int b,
int c, int d)
{
// to store answer
int ans = 0;
// iterate explicitly over all
// possible values of x
for (int i = a; i <= b; i++)
if (d >= Math.Max(c, i + 1))
ans += d - Math.Max(c, i + 1) + 1;
// return answer
return ans;
}
// Driver code
public static void Main()
{
int a = 2, b = 3, c = 3, d = 4;
// function call
Console.WriteLine(NumberOfSolutions(a, b, c, d));
}
}
// This code is contributed
// by Akanksha Rai(Abby_akku)
PHP
= max($c, $i + 1))
$ans += $d - max($c, $i + 1) + 1;
// return answer
return $ans;
}
// Driver code
$a = 2; $b = 3; $c = 3; $d = 4;
// function call
echo NumberOfSolutions($a, $b, $c, $d);
// This code is contributed
// by Akanksha Rai(Abby_akku)
?>
3