Chúng tôi được cung cấp một mảng các phần tử lặp lại hoặc trùng lặp và nhiệm vụ là tìm tích của tất cả các phần tử đó không lặp lại hoặc khác biệt trong mảng đã cho và hiển thị kết quả.
Ví dụ
Input-: arr[] = {2, 1, 1, 2, 3, 4, 5, 5 }
Output-: 120
Explanation-: Since 1, 2 and 5 are repeating more than once so we will take them into
consideration for their first occurrence. So result will be 1 * 2 * 3 * 4 * 5 = 120
Input-: arr[] = {1, 10, 9, 4, 2, 10, 10, 45, 4 }
Output-: 32400
Explanation-: Since 10 and 4 are repeating more than once so we will take them into consideration
for their first occurrence. So result will be 1 * 10 * 9 * 4 * 2 * 45 = 32400 Phương pháp tiếp cận được sử dụng trong chương trình dưới đây như sau -
- Nhập các phần tử trùng lặp vào một mảng
- Để có cách tiếp cận tốt hơn, hãy sắp xếp các phần tử của một mảng theo thứ tự tăng dần để có thể dễ dàng xác định phần tử mảng nào đang lặp lại và không coi phần tử đó là sản phẩm
- Tìm tất cả các phần tử riêng biệt trong một mảng và tiếp tục nhân chúng bằng cách lưu trữ kết quả
- Hiển thị kết quả cuối cùng dưới dạng tích của tất cả các phần tử riêng biệt trong một mảng
Thuật toán
Start
Step 1-> Declare function to find the product of all the distinct elements in an array
int find_Product(int arr[], int size)
Declare and set int prod = 1
Create variable as unordered_set<int> s
Loop For i = 0 and i < size and i++
IF s.find(arr[i]) = s.end()
Set prod *= arr[i]
Call s.insert(arr[i])
End
End
return prod
Step 2 -: In main()
Declare and set int arr[] = { 2, 1, 1, 2, 3, 4, 5, 5 }
Calculate the size of an array int size = sizeof(arr) / sizeof(int)
Call find_Product(arr, size)
Stop Ví dụ
include <bits/stdc++.h>
using namespace std;
//function that calculate the product of non-repeating elements
int find_Product(int arr[], int size) {
int prod = 1;
unordered_set<int> s;
for (int i = 0; i < size; i++) {
if (s.find(arr[i]) == s.end()) {
prod *= arr[i];
s.insert(arr[i]);
}
}
return prod;
}
int main() {
int arr[] = { 2, 1, 1, 2, 3, 4, 5, 5 };
int size = sizeof(arr) / sizeof(int);
cout<<"product of all non-repeated elements are : "<<find_Product(arr, size);
return 0;
} Đầu ra
product of all non-repeated elements are : 120