C++ 中從 1 到 a 和 1 到 b 的數對中,和能被 N 整除的數對個數
給定一個整數陣列,任務是計算可以使用給定陣列值形成的總對數 (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
下面程式中使用的演算法如下
輸入整數變數 a、b 和 n,分別表示從 1 到 a、從 1 到 b,以及與 n 進行可除性比較。
將所有資料傳遞給函式以進行進一步處理。
建立一個臨時變數 count 來儲存數對。
從 i 等於 0 開始,迴圈到 a。
在迴圈內部,從 j 等於 0 開始,迴圈到 b。
在迴圈內部,將 sum 設定為 i + j。
在迴圈內部,檢查 IF sum % n == 0,如果是,則將 count 加 1。
返回 count。
列印結果。
示例
#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
廣告