给我们一个排序后的整数类型元素和一个整数变量x的数组,任务是从给定的数组中形成对,并计算该对中元素的乘积,并检查计算出的乘积是否小于k。
输入值
int arr[] = {2, 7, 1, 0, 8}, int k = 10
输出结果
Count of pairs in a sorted array whose product is less than k are: 7
说明
The pairs that can be formed from the given array are: (2, 7) = 14(greater than k), (2, 1) = 2(less than k), (2, 0) = 0(less than k), (2, 8) = 16(greater than k), (7, 1) = 7(less than k), (7, 0) = 0(less than k), (7, 8) = 56(greater than k), (1, 0) = 0(less than k), (1, 8) = 8(less than k), (0, 8) = 0(less than k). So, the count of pairs with sum less than k are 7.
输入值
int arr[] = {2, 4, 6, 8}, int k = 10
输出结果
Count of pairs in a sorted array whose product is less than k are: 1
说明
The pairs that can be formed from the given array are: (2, 4) = 8(less than k), (2, 6) = 12(greater than k), (2, 8) = 16(greater than k), (4, 6) = 24(greater than x), (4, 8) = 32(greater than k), (6, 8) = 48(greater than k). So, the count of pairs with products less than k is 1.
解决给定问题的方法可以有多种,即幼稚方法和有效方法。因此,让我们首先来看一下幼稚的方法。
输入一个整数元素数组并计算数组的大小并将数据传递给函数
声明一个临时变量计数,以存储乘积小于k的对的计数。
从i到0开始循环直到数组大小
在循环内,从j到i + 1开始另一个循环,直到数组大小
在循环内部,将乘积计算为arr [i] * arr [j],并检查IF product <k,然后将计数加1。
返回计数
打印结果。
输入一个整数元素数组并计算数组的大小并将数据传递给函数
声明一个临时变量数以存储总和小于x的对数。
将arr_0设置为0,将arr_1设置为size-1
从arr_0到arr_1开始FOR循环
在循环内,检查IF arr [arr_0] * arr [arr_1] <x,然后将count设置为count +(arr_1-arr_0)并将arr_0 ++ ELSE递减arr_1 1
返回计数
打印结果。
#include <iostream> using namespace std; int pair_product(int arr[], int size, int k){ int count = 0; int product = 1; for(int i = 0 ; i<size ; i++){ for(int j = i+1; j<size; j++){ product = arr[i] * arr[j]; if(product < k){ count++; } } } return count; } int main(){ int arr[] = {5, 8, 2, 1, 3}; int size = sizeof(arr) / sizeof(arr[0]); int k = 10; cout<<"Count of pairs in a sorted array whose product is less than k are: "<<pair_product(arr, size, k); return 0; }
输出结果
如果我们运行上面的代码,它将生成以下输出-
Count of pairs in a sorted array whose product is less than k are: 5
#include <iostream> using namespace std; int pair_product(int arr[], int size, int k){ int arr_0 = 0; int arr_1 = size-1; int count = 0; int product = 1; while(arr_0 < arr_1){ product = arr[arr_0] * arr[arr_1]; if (product < k){ count = count + (arr_1 - arr_0); arr_0++; } else{ arr_1--; } } return count; } int main(){ int arr[] = {1, 3, 4, 2, 1}; int size = sizeof(arr) / sizeof(arr[0]); int k = 5; cout<<"Count of pairs in a sorted array whose product is less than k are: "<<pair_product(arr, size, k); return 0; }
输出结果
如果我们运行上面的代码,它将生成以下输出-
Count of pairs in a sorted array whose product is less than k are: 10