Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C++

จำนวนคู่จาก N จำนวนธรรมชาติลำดับแรกที่ผลรวมหาร K ลงตัวใน C++


ให้ N และ K หาจำนวนคู่จาก 1..N ที่ผลรวมหาร K ลงตัว

ตัวอย่าง:

Input: N = 3, K = 2
Output: 1

คู่ (1, 3) ผลรวม 4 หาร 2 ลงตัว

อัลกอริทึม

  • กำหนด N, K
  • สร้างอาเรย์ 1..N
  • count = 0
  • วนลูป 2 ชั้นหาทุกคู่:
    • sum = arr[i] + arr[j]
    • ถ้า sum % K == 0 count++
  • คืนค่า count

การเขียนโปรแกรม C++

#include <bits/stdc++.h> using namespace std; int get2PowersCount(vector<int> arr, int N, int K) {    int count = 0;    for (int i = 0; i < N; i++) {       for (int j = i + 1; j < N; j++) {          int sum = arr[i] + arr[j];          if (sum % K == 0) count++;       }    }    return count; } int main() {    vector<int> arr;    int N = 10, K = 5;    for (int i = 1; i <= N; i++) arr.push_back(i);    cout << get2PowersCount(arr, N, K) << endl;    return 0; }

ผลลัพธ์

9