Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> C++

Tích các cặp phần tử liên tiếp trong mảng trong C++


Cho mảng arr[]. Nhiệm vụ: tính tích của các cặp phần tử liên tiếp (arr[i] × arr[i+1]).

Ví dụ 1

Input – arr[] = {1, 2, 3, 4}

Output – 2, 6, 12

Giải thích: Cặp (1,2)=2, (2,3)=6, (3,4)=12.

Ví dụ 2

Input – arr[] = {9, 5, 1, 2, 6, 10}

Output – 45, 5, 2, 12, 60

Thuật toán

  1. Duyệt i từ 0 đến n-2.
  2. Tính product = arr[i] * arr[i+1].
  3. In hoặc lưu kết quả.

Ví dụ code

#include <iostream>
#include <vector>
using namespace std;

vector<long long> pairwiseProducts(int arr[], int n) {
    vector<long long> res;
    for (int i = 0; i < n - 1; i++) {
        res.push_back(1LL * arr[i] * arr[i + 1]);
    }
    return res;
}

int main() {
    int arr[] = {2, 4, 6, 8, 10, 12, 14};
    int n = sizeof(arr) / sizeof(arr[0]);
    
    auto products = pairwiseProducts(arr, n);
    cout << "Pairwise products: ";
    for (long long p : products) cout << p << ' ';
    cout << endl;
    return 0;
}

Kết quả

Pairwise products: 8 24 48 80 120 168

Độ phức tạp: O(N) thời gian, O(N) không gian (nếu lưu kết quả).