用 C++ 查詢滿足 a % b = k 陣列中的所有對 (a, b)
假設我們有一個數組 A,從該陣列中,我們必須找出所有滿足 a%b = k 的對 (a, b)。假設陣列 A = [2, 3, 4, 5, 7],且 k = 3,則對為 (7, 4)、(3, 4)、(3, 5)、(3, 7)。
為了解決此問題,我們將遍歷列表並檢查給定的條件是否滿足。
示例
#include <iostream>
using namespace std;
bool displayPairs(int arr[], int n, int k) {
bool pairAvilable = true;
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if (arr[i] % arr[j] == k) {
cout << "(" << arr[i] << ", "<< arr[j] << ")"<< " ";
pairAvilable = true;
}
}
}
return pairAvilable;
}
int main() {
int arr[] = { 2, 3, 4, 5, 6, 7 };
int n = sizeof(arr) / sizeof(arr[0]);
int k = 3;
if (displayPairs(arr, n, k) == false)
cout << "No paira found";
}輸出
(3, 4) (3, 5) (3, 6) (3, 7) (7, 4)
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
JavaScript
PHP