给我们一个整数数组,任务是计算使用给定数组值可以形成的对的总数(x,y),以使x的整数值小于y。
输入-int a = 2,b = 3,n = 2
输出-从1到a和从1到b的对数,其和可被N整除为-3
说明-
Firstly, We will start from 1 to a which includes 1, 2 Now, we will start from 1 to b which includes 1, 2, 3 So the pairs that can be formed are (1,1), (1,2), (1, 3), (2, 1), (2, 2), (2, 3) and their respective sum are 2, 3, 4, 3, 4, 5. The numbers 2, 4, 4 are divisible by the given N i.e. 2. So the count is 3.
输入-int a = 4,b = 3,n = 2
输出-从1到a和从1到b的对数,其和可被N整除为-3
说明-
Firstly, We will start from 1 to a which includes 1, 2, 3, 4 Now, we will start from 1 to b which includes 1, 2, 3 So the pairs that can be formed are (1,1), (1,2), (1, 3), (2, 1), (2, 2), (2, 3), (3,1), (3, 2), (3, 3), (4, 1), (4, 2), (4, 3) and their respective sum are 2, 3, 4, 3, 4, 5, 4, 5, 6, 5, 6, 7. The numbers 3, 3, 6, 6 are divisible by the given N i.e. 3. So the count is 4
输入1到a,1到b的整数变量a,b和n以及与n的除数比较
将所有数据传递给函数以进行进一步处理
创建一个临时变量计数以存储对
从i到0开始循环直到a
在循环内,从j到0直到b开始另一个循环FOR
在循环内,用i + j设置和
在循环内部,检查IF sum%n == 0,然后将计数加1
返回计数
打印结果
#include <iostream> using namespace std; int Pair_a_b(int a, int b, int n){ int count = 0; for (int i = 1; i <= a; i++){ for (int j = 1; j <= b; j++){ int temp = i + j; if (temp%n==0){ count++; } } } return count; } int main(){ int a = 2, b = 20, n = 4; cout<<"Count of pairs from 1 to a and 1 to b whose sum is divisible by N are: "<<Pair_a_b(a, b, n); return 0; }
输出结果
如果我们运行上面的代码,它将生成以下输出-
Count of pairs from 1 to a and 1 to b whose sum is divisible by N are: 10